Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

165
Views
Usando tubería asíncrona con ngIf

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>
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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:

  1. Suscribiendo a lo observable (o then'ing en el caso de una promesa),
  2. Salida de algo cada vez que se emite un nuevo valor, capturándolo en una variable llamada value
  3. Realización de la comprobación de value if
  4. Procesar condicionalmente las cosas dentro ng-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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!