Typescript:
getMyList(): Observable<ApiResponse> {
return this.http.get<ApiResponse>(this.myListUrl);
}
this.myList = getMyList();
HTML:
<ng-select [items]="myList | async">
The List:
Id: 1, Name: foo; Id: 2, Name: bar; ...
Earlier I did something like this, but this does not work async (with the pipe):
getList().subscribe(data => {
data.result.forEach(entry => {
this.myList.push(entry.Name);
});
});
I read something with mapping the Observable ApiResponse to an Observable MyList, but I have no idea how to do this. Looking for advice
You can find here a stackblitz demo on how to use HttpClient
, Observable
and async
pipe.
Please may I suggest you some best practices :
Use $
after your observable variable name to clearly distinguish it from other non observable variable. You should use async
pipe with observable.
Needless to make a subscription to fill an array. Observables are very powerful with async
pipe.
Distinguish with your model the API
response, and the item model in inside. (if it's the case). You can see in my example, that get
returns a ApiResponse
model, but after we are retrieving an array of ApiItem
.
Update:
HttpClient.get
returns an Observable. It's like a pipeline. You can then define a chain of operators, and each time a data is emitted, it will pass througth this pipeline, in order to be transformed.
In this example, api returns a ApiResponse
object, with one unique property : an array of ApiItem.
map
operator transforms the input value. Here, it returns the list of items.
You will find a lot of good tutorials about Observables and pipe operators. For example HTTP Example with Observables from Asim.
Hope this could help you a little.
Yes! That really help, but can you explain further what (map(response => response.items) does? where comes the first and the second response from?
I have a structure like this:
export class ApiResponse { status: number; message: number; result: any; }
export class myList{ id: number; name: string; }
solved it myself.
this.myList$ = this.apiService.getMyList().pipe(map(result => result.result));
Thanks a lot for that great stackblitz demo! It helped a lot!I updated my answer with more details.