我经常遇到使用*ngIf
. 通常,返回 boolean 的函数内部有一个 subscribe 。由于多次检查该指令,因此最终会发出多个请求并且页面崩溃。我真的不知道如何解决它。下面是一个例子:
我的Service.service.ts:
myFunction(argument: any): Observable<boolean> {
// body that returns the observable using HttpClient
}
MyComponent.component.ts:
constructor(private myService: MyService){}
verifySomething(value: number): boolean {
this.myService.function(value).subscribe((aux) => v); // this is supposed to return what is inside of subscribe to the "upper-function" (verifySomething)
}
MyComponent.component.html:
<tag *ngIf="verifySomething(entity.id)">irrelevant</tag>
我的第一个选择是使用“标志”变量来做一个变通方法,该变量检查输入发生了多少次……但我认为这不是最好的方法。
编辑:更多细节
MyComponent.component.html:
<div *ngIf="values$ | async as values">
<tbody>
<tr *ngFor="let value of values.content">
<td *ngIf="verifySomething(value.id)"> {{ value.property1 }}
<td *ngIf="verifySomething(value.id)"> {{ value.property2 }}
</tr>
</tbody>
</div>
你可以用async
管道解决你的问题。多亏了它,我们可以async
在模板中使用变量。
首先,verifySomething
函数必须返回 observable。
verifySomething(value: number): Observable<boolean> {
return this.myService.function(value);
}
然后,我们需要更新模板文件。它必须使用async
带有*ngIf
指令的管道。
<tag *ngIf="verifySomething(entity.id) | async">irrelevant</tag>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句