使用异步管道订阅对象的属性

edd*_*edd 0 object subscription rxjs angular

以这种方式订阅对象的属性有什么缺点吗:

    <th [attr.colspan]="(headerColSpan$ | async).aaa">...</th>
    <th [attr.colspan]="(headerColSpan$ | async).bbb" >...</th>
    <th [attr.colspan]="(headerColSpan$ | async).ccc">...</th>
    <th [attr.colspan]="(headerColSpan$ | async).ddd" >...</th>
Run Code Online (Sandbox Code Playgroud)
    this.headerColSpan$ = new Observable((subscriber) => {
    subscriber.next(this.headerColspan);
    });

    this.headerColspan = {aaa: 2, bbb: 3, ccc: 1, ddd: 5};
Run Code Online (Sandbox Code Playgroud)

它似乎是这样工作的,但我不确定它在 RxJS 应该如何使用的意义上是否正确。

另一种方法是创建四个BehaviorSubjects。每个 colspan 一个。

出于某种原因,这样会更好吗?

Ame*_*mer 5

您可以使用async管道一次,并将其结果分配给模板变量,然后使用它来访问您需要的属性,如下所示:

<ng-container *ngIf="headerColSpan$ | async as headerColSpan">
  <th [attr.colspan]="headerColSpan.aaa">...</th>
  <th [attr.colspan]="headerColSpan.bbb">...</th>
  <th [attr.colspan]="headerColSpan.ccc">...</th>
  <th [attr.colspan]="headerColSpan.ddd">...</th>
</ng-container>
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

1027 次

最近记录:

3 年,6 月 前