首页 > 解决方案 > 如何在html中实现异步管道但在返回数据时仍然能够调用函数

问题描述

我已经在 Angular 5 中实现了一个异步管道。它按预期工作,但我希望能够在从后端返回数据时调用一些函数并分配变量(即设置 seo 详细信息、广告定位、)

在不使用异步管道的情况下,我像这样调用服务:

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

但是,使用异步管道,我看不到如何选择对打字稿中的返回数据做任何事情。

这就是我实现异步管道的方式:

打字稿

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>

有任何想法吗?

标签: javascriptangularecmascript-5

解决方案


使用水龙头运算符

Tap 运算符对于与 Observable 的返回值不直接相关的副作用或更改很有用

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

推荐阅读