[英]Angular function being called multiple times
I have a component method that I'm invoking for the template. 我有一个正在调用模板的组件方法。
For example: 例如:
export class Component {
isValid(id): Observable<boolean> {
return service.isValid(id)
}
}
<div *ngIf="isValid(1) | async"></div>
<div *ngIf="isValid(2) | async"></div>
<div *ngIf="isValid(3) | async"></div>
The isVaild method returns an observable. isVaild方法返回一个可观察值。 The problem is that in each change detection cycle Angular calls the isValid method which returns a new observable.
问题在于,在每个更改检测周期中,Angular都会调用isValid方法,该方法返回一个新的可观察对象。
What is the solution to this kind of situations? 对这种情况有什么解决方案?
If subscribe to the service then you'll use that logic in callback function like so 如果订阅该服务,那么您将在回调函数中使用该逻辑,如下所示
export class Component {
isValid: boolean;
isValid(id) {
service.isValid(id).subscribe(response => {
this.isValid = response;
});
}
}
Then in template you dont need to call isValid
function and no need to use | async
然后在模板中,您不需要调用
isValid
函数,也无需使用| async
| async
<div *ngIf="isValid(1)"></div>
<div *ngIf="isValid(2)"></div>
<div *ngIf="isValid(3)"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.