当我尝试绑定像这样的异步函数时,我得到一个无限循环:
<tr *ngFor="let i of items">
<td>{{myAsyncFunc(i) | async}}</td>
</tr>
Run Code Online (Sandbox Code Playgroud)
这是功能:
private myAsyncFunc(i: string): Promise<string> {
return Promise.resolve("some");
}
Run Code Online (Sandbox Code Playgroud)
我做错了什么?或者这是一个错误?
Joh*_*lph 15
你myAsyncFunc(i: string)在每次通话时都会返回一个新的Promise ,这就是你获得"无限循环"的原因.尝试返回相同的Promise实例;-)
"无限循环"实际上不是传统的无限循环,而是async管道在其输入Promise解析时触发变化检测周期的副作用.在这个新的变化检测周期中,angular将调用myAsyncFunc(i: string)并获得一个新的Promise来观察,然后解决整个事情再次开始.
小智 5
如果您的 async/observable 要求您传递一个参数(例如,您位于 ngFor 循环内),也许您可以为此创建一个自定义异步管道。
@Pipe({
name: 'customPipe'
})
export class customPipe implements PipeTransform {
constructor(private someService: SomeService) {}
/**
*
* @param id
*/
transform(id: number): Observable<boolean> {
return this.someService.shouldShow(id);
}
}
Run Code Online (Sandbox Code Playgroud)
在您的模板中,您可以将异步管道称为:
<td>{{id | customPipe | async}}</td>
Run Code Online (Sandbox Code Playgroud)