我对棱角和承诺有问题,我不明白。
这是我的html:
<div>Is Ready? {{isReady}}</div>
<div *ngIf="isReady">Show this</div>
<div *ngIf="!isReady">Show that</div>这是我的TS文件:
isReady: boolean = false;
constructor(
private myService: MyService){
await this.giveMeSlowData();
}
async giveMeSlowData() : Promise<void>{
console.log(await this.myService.getResult());
this.isReady = await this.myService.getResult();
}通常,此{{}}中的HTML中的所有内容都会在TS文件中的变量一出现变化。但不是现在。我可以在5-6秒后看到控制台日志,但是HTML不会改变。为什么?
谢谢大家!
发布于 2022-10-25 20:32:01
有几个原因可以解释为什么直到你得到你的控制台日志之后才能完成。
实际问题
您有一个从不返回任何内容的async方法。这就让Promise永远悬着。由于在构造函数中对挂起的await进行调用,组件将永远不会完成初始化。您可以通过在ngOnInit中添加日志语句来测试这一点。
建议
,
MyService的任何逻辑,如果必须保持为Promise-based类.,则这种逻辑非常方便。
所有初始化逻辑应该在一个constructor.方法中处理,而不是在方法中处理。
async管道。解决方案
这就是所有这些都是如何结合在一起的。
slow-data.component.ts
isReady: Subject<boolean> = new BehaviorSubject(false);
constructor(
private myService: MyService,
) {
}
ngOnInit(): void {
giveMeSlowData();
}
giveMeSlowData(): void {
from(this.myService.getResult()).subscribe(isReady);
}slow-data.component.html
<div>Is Ready? {{isReady | async}}</div>
<div *ngIf="isReady | async">Show this</div>
<div *ngIf="!(isReady | async)">Show that</div>发布于 2022-10-25 16:50:47
为什么要给this.myService.getResult()打两次电话?试试这个:
async giveMeSlowData() : Promise<void>{
this.isReady = await this.myService.getResult();
console.log(this.isReady);
}https://stackoverflow.com/questions/74197487
复制相似问题