Para la propiedad de status declarada y rellenada como se muestra a continuación:
public status:Promise<String>; constructor() { this.status = this.getStatus(); } public getStatus():Promise<String>{ return new Promise((resolve,reject)=>{ setTimeout(()=>{ resolve('stable'); },2500); }); } ¿Alguien podría explicar cómo funciona la tubería async a continuación?
<span *ngIf="status|async"> {{ status|async }} </span>Tiendo a combinar *ngIf y async así:
Mi componente tendrá un Observable (o en su caso una Promesa), con un nombre de variable que termina con $ . Este patrón de nomenclatura proviene de la guía de nomenclatura observable aquí
@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); } }Entonces mi plantilla:
<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>La plantilla esencialmente se lee como:
if(somevalue) render a div displaying the value else render a div with text "The value was null..." La clave es que async es una pipe . Una pipe siempre transforma alguna entrada. En este caso, estamos pasando un observable (o una promesa) y obteniendo algún resultado.
Así que poniéndolo todo junto, la plantilla es:
then'ing en el caso de una promesa),valuevalue ifng-container o usar la plantilla marcada con #other¡Aquí hay un stackblitz que demuestra lo anterior!
Aparte, reconozco que mi ejemplo es usar Observable en lugar de Promises. Según tengo entendido, esencialmente funcionan de la misma manera. Sin embargo, recomiendo enfáticamente usar Observables sobre Promises en cualquier aplicación Angular. Los observables son mucho más flexibles y creo que te encontrarás con un comportamiento mucho menos confuso.