Jan Bürger
Jan Bürger

Reputation: 121

How to use the async pipe with an Observable<ApiResponse>

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

Upvotes: 0

Views: 173

Answers (1)

Thierry Falvo
Thierry Falvo

Reputation: 6280

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.

Upvotes: 1

Related Questions