Cle*_*mzd 3 promise angular-promise angular
我正在尝试做一个 ngIf ,其结果取决于承诺。
模板
<div>
<select [(ngModel)]="carValue" name="carName">
<option value="renault">Renault</option>
<option value="bmw">Bmw</option>
</select>
<p *ngIf="isDisplayed()">Good choice!</p>
</div>
Run Code Online (Sandbox Code Playgroud)
到目前为止,函数 isDisplayed 是
isDisplayed() {
return this.carValue === 'bmw';
}
Run Code Online (Sandbox Code Playgroud)
但我希望它是异步的。就像是
isDisplayed() {
return this.getBestChoice().then((result) => result);
}
getBestChoice() {
// fake http call
return new Promise((resolve) => {
setTimeout(() => resolve('bmw'), 3000);
});
}
Run Code Online (Sandbox Code Playgroud)
显然这是行不通的。我有如何实现这个的想法,但不确定它是否干净。
这是一个朋克。
我是这样解决的:
类.ts
export class FieldHeaderSectionComponent implements OnInit {
hasBody: Promise<boolean>;
constructor() {
this.hasBody = this.haveBody();
}
public haveBody() : Promise<boolean> {
// ... logic
return Promise.resolve(false);
}
}
Run Code Online (Sandbox Code Playgroud)
模板.html
<div *ngIf="hasBody | async">...</div>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6970 次 |
| 最近记录: |