Search code examples
javascriptangularecmascript-5

How to implement an async pipe in html but still be able to call functions when data is returned


I've implemented an async pipe in angular 5. It works as expected but I would like to be able to call a few functions and assign variables when data is returned from the backend (i.e. set seo details, ads targeting, )

Without using the async pipe I made the call to the service like this:

    this._dataService.send(new BrochureRequest(this._stateService.params.propertyId)).subscribe((httpResponse) => {
     this.httpResponse$ = httpResponse;
        // do more stuff
     });

However, with the async pipe I don't see how I have the option of doing anything to the return data in the typescript.

This is how I've implemented the async pipe :

typescript

this.httpResponse$ = this._dataService
      .send(new BrochureRequest(this._stateService.params.Id));

html

 <div *ngIf="httpResponse$ | async as httpResponse; else loading">
       {{httpResponse | json}}
 </div>

 <ng-template #loading>
     loading ...
 </ng-template>

Any ideas?


Solution

  • Use tap operator

    The tap operator is useful for side effects or changes that don’t relate directly to the returned value of the Observable

    this.httpResponse$ = this._dataService
              .send(new BrochureRequest(this._stateService.params.Id)).pipe(tap(data=> console.log(data)));