【问题标题】:Subscribe to params and use observable in template with async订阅参数并在模板中使用可观察的异步
【发布时间】:2022-01-01 20:58:35
【问题描述】:

我想从当前 url 获取配置文件 ID。我正在做类似的事情

opaProfileId$ = this.activatedRoute.queryParamMap.subscribe((params) => +params.get('opaProfileId'));

然后在模板中我想将它与类似的数字进行比较

<tr [ngClass]="{ 'highlight-row': profile.id === opaProfileId$ | async as number }" *ngFor="let profile of data">

但它会引发错误。任何想法如何用 observable 做到这一点?

【问题讨论】:

  • 不要订阅,这就是async 管道为您所做的(并取消订阅) 现在您正在为opaProfileId$. 分配订阅
  • 只说it throws error 而不提供错误不是很有帮助。这就像说“它不起作用”

标签: javascript angular typescript rxjs observable


【解决方案1】:

不能在组件中合并订阅和模板中的async 管道。

组件控制器中的订阅

您要么在组件控制器中订阅,要么在模板中使用async。在控制器中订阅时,最好在组件关闭时关闭订阅。请参阅here 了解更多信息。

opaProfileId: number;

this.activatedRoute.queryParamMap.subscribe((params) => 
  this.opaProfileId = +params.get('opaProfileId')
);
<tr [ngClass]="{ 'highlight-row': profile.id === opaProfileId }" *ngFor="let profile of data">

async管道

使用async 管道时,您需要使用RxJS map 运算符来获取查询参数和类型转换。使用async 时,无需显式关闭订阅。 async pipe 负责处理。

opaProfileId$: Observable<number>;

this.opaProfileId$ = this.activatedRoute.queryParamMap.pipe(
  map((params) => +params.get('opaProfileId'))
);
<tr [ngClass]="{ 'highlight-row': profile.id === (opaProfileId$ | async) }" *ngFor="let profile of data">

【讨论】:

  • 非常有帮助。非常感谢:)
猜你喜欢
  • 2019-06-19
  • 1970-01-01
  • 1970-01-01
  • 2019-07-10
  • 2016-07-10
  • 2018-05-01
  • 2018-11-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多