[英]Using async pipe with ngIf
對於聲明和填充的status
屬性,如下所示:
public status:Promise<String>;
constructor() {
this.status = this.getStatus();
}
public getStatus():Promise<String>{
return new Promise((resolve,reject)=>{
setTimeout(()=>{
resolve('stable');
},2500);
});
}
有人可以解釋下面的async
管道是如何工作的嗎?
<span *ngIf="status|async">
{{ status|async }}
</span>
我傾向於像這樣將*ngIf
和async
結合起來:
我的組件將有一個 Observable(或在您的情況下是 Promise),其變量名稱以$
結尾。 此命名模式來自此處的 observable 命名指南
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
//Create a subject with an initial value
//Keep the subject private so only this component may emit value
private _mySubject = new BehaviorSubject<any>('initial value!');
//Expose the observable as a public variable
//This allows the template to listen for values
get myObservable$() {
return this._mySubject.asObservable();
}
//helpers for demo!
emitNull() {
this._mySubject.next(null);
}
emitUndefined() {
this._mySubject.next(undefined);
}
emitNumber(number) {
this._mySubject.next(number);
}
emitText(text) {
console.log(text);
this._mySubject.next(text);
}
}
然后我的模板:
<div>
<button (click)="emitNull()">Emit Null</button>
</div>
<div>
<button (click)="emitUndefined()">Emit Undefined</button>
</div>
<div>
<button (click)="emitNumber(num.value)">Emit Number</button>
<input type="number" #num value="42" />
</div>
<div>
<button (click)="emitText(txt.value)">Emit String</button>
<input type="text" #txt value="foo" />
</div>
<br />
<h1>Value:</h1>
<ng-container *ngIf="myObservable$ | async as value; else other">
<div>{{ value }}</div>
</ng-container
>
<ng-template #other>
<div>The value was null, undefined or empty string</div>
</ng-template>
該模板本質上是這樣的:
if(somevalue)
render a div displaying the value
else
render a div with text "The value was null..."
關鍵是async
是一個pipe
。 pipe
總是轉換一些輸入。 在這種情況下,我們傳入一個可觀察的(或承諾)並獲得一些輸出。
所以把它們放在一起,模板是:
then'ing
在一個承諾的情況下),value
的變量中value
執行if
檢查ng-container
的東西或使用標有#other
的模板順便說一句,我認識到我的例子是使用 Observable 而不是 Promises。 據我了解,它們的工作原理基本相同。 但是,我強烈建議在任何 Angular 應用程序中使用 Observables 而不是 Promises。 Observables 更加靈活,我認為你會遇到不那么令人困惑的行為。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.