Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/28.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在模板中调用的角度模型方法在无止境循环中执行_Javascript_Angular_Typescript_Angular2 Template - Fatal编程技术网

Javascript 在模板中调用的角度模型方法在无止境循环中执行

Javascript 在模板中调用的角度模型方法在无止境循环中执行,javascript,angular,typescript,angular2-template,Javascript,Angular,Typescript,Angular2 Template,在我的angular应用程序中,我定义了模型类: 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 `Hell

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

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[])
    }))

  }
它工作得很好,在我的组件中,我得到案例实例。我正在将这些实例传递给其他子组件:

<app-case-listing [case]="case" *ngFor="let case of cases"></app-case-listing>
因此,我的问题是:

  • 这是正确的行为吗
  • 如果没有-如何修复/优化代码

  • 这是正确的行为,在
    ngFor
    循环中调用
    isPending
    方法,该方法调用每个
    案例
    实例。您可以将ChangeDetectionStrategy.OnPush添加到
    应用程序案例列表
    组件中,以避免不必要的检查

    <li [class.pending]="case.isPending()">
      li element for case {{case.customMethod}}, {{case.status}}
    </li>
    
    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