【问题标题】:Use async pipe in other async pipe在其他异步管道中使用异步管道
【发布时间】:2023-03-29 16:25:01
【问题描述】:

我想在带有另一个异步管道的角度模板中使用异步管道。

问题是我的第二个异步管道返回null,所以没有打印。但是我的第一个异步管道运行良好。

那么我该如何在我的 html 模板中打印我的 zone.title 呢?我只能通过doSomething(id) 方法获得它。

template.component.html

<div *ngFor="let site of sites$ | async">
  <p>{{site.title}}</p>
  <div *ngIf="doSomething(site.id) | async as zone">
     <p>{{zone?.title}}<p>
  </div>
</div>

template.component.ts

public sites$: Observable<{id: string, title: string}[]>;

constructor(private siteService: SiteService) {}

ngOnInit() {
  this.sites$ = this.siteService.getSites();
}

doSomething(id: string): Observable<{id: string, title: string}> {
  return this.siteService.getZoneById(id);
}

site.service.ts

constructor(private http: HttpClient) {}

getSites(): Observable<{id: string, title: string}[]> {
  this.http.get(...);
}

getZoneById(id: string): Observable<{id: string, title: string}> {
  this.http.get(...);
}

【问题讨论】:

    标签: angular rxjs observable


    【解决方案1】:

    在模板中调用函数通常不是一个好主意,因为它会导致不可预测的结果。

    所以你可以重构你的代码:

    template.component.html

    <div *ngFor="let site of sites$ | async">
      <p>{{site.title}}</p>
      <div *ngIf="site.zone$ | async as zone">
         <p>{{zone?.title}}<p>
      </div>
    </div>
    

    template.component.ts

    public sites$: Observable<{
      id: string,
      title: string,
      zone$: Observable<{id: string, title: string}>
    }[]>;
    
    constructor(private siteService: SiteService) {}
    
    ngOnInit() {
      this.sites$ = this.siteService.getSites().pipe(
        map((sites) => {
          return sites.map(site => {
            return {
              id: site.id,
              title: site.title,
              zone$: this.doSomething(site.id),
            };
          })
        })
      );
    }
    
    doSomething(id: string): Observable<{id: string, title: string}> {
      return this.siteService.getZoneById(id);
    }
    

    查看我的Stackblitz example

    【讨论】:

    • 谢谢,所以您建议我在我的 ts 中创建一种新的数据格式并使用它。很高兴知道!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-18
    • 2017-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-02
    • 2017-09-09
    相关资源
    最近更新 更多