在模板中调用的角模型方法在无限循环中执行

时间:2019-05-17 13:35:14

标签: javascript angular typescript angular2-template

在我的角度应用程序中,我定义了模型类:

import {Type} from "class-transformer"; //https://github.com/typestack/class-transformer

export class Case {
  id: string;

  @Type(() => Date)
  created: string;
  status: string;

  get customMethod() {
    return `Hello ${this.id}`;
  }

  isPending() {
    console.log('isPending() called...');
    return this.status == 'new';
  }

}

在我的组件中,我从rest api获取案例:

  ngOnInit() {
    this.api.getCases().subscribe((cases) => {
      this.cases = cases;
    });
  }

和getCases()看起来像:

import {plainToClass} from "class-transformer";
import {Case} from "../models/Case";

// ... come other code

  public getCases() {
    return this.http.get(`${this.apiUrl}/cases`).pipe(map(response => {
      return plainToClass(Case, response as Case[])
    }))

  }

工作正常,在我的组件中,我获得了Case实例。我将这些实例传递给其他子组件:

<app-case-listing [case]="case" *ngFor="let case of cases"></app-case-listing>

那个子组件模板就是:

<li [class.pending]="case.isPending()">
  li element for case {{case.customMethod}}, {{case.status}}
</li>

所有方法都可以正常工作-除了isPending()似乎是在循环中调用之外。我不确定这是否是预期的行为(或者在性能方面是否良好)。当我将控制台日志添加到“ customMethod” getter时,其日志也会循环登录。

控制台输出看起来像(成千上万条这样的消息):

isPending() called...
6
breadcrumbs.js:58 isPending() called...
zone.js:2279 [Violation] 'setTimeout' handler took 168ms
6
breadcrumbs.js:58 isPending() called...
6
breadcrumbs.js:58 isPending() called...
zone.js:2279 [Violation] 'setTimeout' handler took 185ms
6
breadcrumbs.js:58 isPending() called...
6
breadcrumbs.js:58 isPending() called...
zone.js:2279 [Violation] 'setTimeout' handler took 186ms
6
breadcrumbs.js:58 isPending() called...
6
breadcrumbs.js:58 isPending() called...
6
breadcrumbs.js:58 isPending() called...
6
breadcrumbs.js:58 isPending() called...
zone.js:2279 [Violation] 'setTimeout' handler took 197ms

所以,我的问题是:

  1. 这是适当的行为吗?
  2. 如果不是-我该如何修复/优化代码?

1 个答案:

答案 0 :(得分:1)

这是正确的行为,您在isPending循环内调用ngFor方法,并且该方法为每个Case实例调用。您可以将ChangeDetectionStrategy.OnPush添加到app-case-listing组件中,以避免不必要的检查。