繁体   English   中英

我如何在 ngIf 条件 Angular 中使用 function

[英]how can i use a function in ngIf condition Angular

我有 2 个功能

loadItems(): void {
this.service.query().subscribe((res: HttpResponse<Item[]>) => 
 (this.items = res.body || []));
 }
 
loadAuditByItem(item: Item) {
this.service.auditByItem(item.id!).subscribe((res: HttpResponse<ItemAudit[]>) => 
(this.auditByItem = res.body || []));
 }

我想在同一页面上显示来自 loadItems() 和 loadAuditByItem() 的信息我设法从 loadItems() 显示名称和描述,但我需要从 loadAuditByItem(item) 显示“createdBy”

<div *ngFor="let item of items">
    <div *ngIf="loadAuditByItem(item)">
        <span>Name: {{ item.name}}</span>
        <span>Description : {{ item.description }}</span>
        <span>Created by: {{ auditByItem .createdBy}}</span>
    </div>
</div>

我会返回 Observable 以便 *ngIf 使用AsyncPipe处理订阅。

public loadAuditByItem(item: Item): Observable<any> {
    return this.service.auditByItem(item.id!);
}
<div *ngFor="let item of items">
    <div *ngIf="loadAuditByItem(item) | async as audit">
        <span>Name: {{ item.name }}</span>
        <span>Description : {{ item.description }}</span>
        <span>Created by: {{ audit.createdBy }}</span>
    </div>
</div>

在 ngIf 中调用ngIf对性能非常不利(你可以添加一个console.log并检查你的控制台以查看它被调用了多少次)而不是你可以使用Pipes ,据说让我给你一个解决方案你的用例:

import { forkJoin, Observable, of, Subject } from "rxjs";
import { map, switchMap } from "rxjs/operators";
...

  public items$: Observable<Item[]>;

...

  loadItems(): void {
    // please consider to edit your backend API to return all data in one API call
    // since this nested calls will lead to N+1 calls problem.

    this.items$ = this.service.query().pipe(
      map((res: HttpResponse<[]>) => res.body || []),
      switchMap((items: []) => {

        if (items.length === 0) {
          return of([]);
        }

        return forkJoin(
          items.map((item: any) =>
            this.service.auditByItem(item.id).pipe(
              map(audit => {
                item.audit = audit;
                return item;
              })
            )
          )
        );
      })
    );
  }
<div *ngFor="let item of (items$ | async)">
    <div>
        <span>Name: {{ item.name}}</span>
        <span>Description : {{ item.description }}</span>
        <span>Created by: {{ item.audit.createdBy}}</span>
    </div>
</div>

奖励:从服务中暴露HttpResponse不好,最好只返回Item[]并将HttpResponse封装在那里。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM