Javascript 在模板中调用的角度模型方法在无止境循环中执行
在我的angular应用程序中,我定义了模型类: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
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