【问题标题】:How to do a ngIf based on a promise in angular?如何根据角度的承诺做一个ngIf?
【发布时间】:2018-08-25 10:36:03
【问题描述】:

我正在尝试执行 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>

到目前为止,函数isDisplayed是

isDisplayed() {
  return this.carValue === 'bmw';
}

但我希望它是异步的。类似的东西

isDisplayed() {
  return this.getBestChoice().then((result) => result);
}

getBestChoice() {
  // fake http call
  return new Promise((resolve) => {
    setTimeout(() => resolve('bmw'), 3000);  
  });
}

显然它不会起作用。我有想法如何实现它,但不确定它是否干净。

  • 绑定事件 ngModelChange。每次用户挑选一辆新车。它重新加载一个变量“isDisplayed”
  • 保存承诺并在模板中使用 aync 管道。但它不会重新加载数据。

这是punker

【问题讨论】:

  • 只在你的组件中有一个displayed 属性,异步方法更新,并在上面使用*ngIf?在*ngIf/*ngFor/etc 中调用方法通常被认为是不好的做法。顺便说一句。
  • 最佳选择会随着时间而改变吗?每次用户更改是 select 中的选择时,您是否必须重新获取它?
  • @all 我需要在每次选择汽车时重新加载“最佳选择”
  • @Clemzd,为什么不使用变量? this.getBestChioce().then(result=>this.variable=result) 和 *ngIf="variable"
  • @Eliseo 变量将适用于第一次调用,但如果用户更换汽车,它将不会再次调用承诺

标签: angular promise angular-promise


【解决方案1】:

为什么不使用 Observables,它是 Angular 的方式。您可以将一个设置为公共属性并通过 AsyncPipe 运行它,它将为您处理 sub/unsub 和更改检测触发。

import { Component } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { timer } from 'rxjs/observable/timer';
import { map, share, tap } from 'rxjs/operators';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  carValue = '';
  showCongrats$: Observable<boolean>;
  check() {
    // fake API call
    this.showCongrats$ = timer(1000).pipe(
      map(() => 'bmw'), // "API" says bmw rocks
      tap(console.log),
      map(bestCar => this.carValue === bestCar),
      share() // so multiple async pipes won't cause multiple API calls
    );
  }
}

模板:

<div>
    <select [(ngModel)]="carValue" (change)="check()">
    <option value="">Choose</option>
    <option value="renault">Renault</option>
    <option value="bmw">Bmw</option>
  </select>
    <p *ngIf="showCongrats$|async">Good Choice!</p>
    <p *ngIf="carValue && (showCongrats$|async) === false">Not the Best Choice!</p>
</div>

工作堆栈闪电战: https://stackblitz.com/edit/angular-cxcq89?file=app%2Fapp.component.ts

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-27
    • 1970-01-01
    • 2018-08-16
    • 1970-01-01
    • 2016-10-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多