如何根据角度的承诺做一个ngIf?

时间:2018-03-16 11:13:32

标签: angular promise angular-promise

我正在尝试使用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”
  • 保存承诺并在模板中使用异步管道。但它不会重新加载数据。

这是punker

2 个答案:

答案 0 :(得分:2)

为什么不选择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>

使用stackblitz: https://stackblitz.com/edit/angular-cxcq89?file=app%2Fapp.component.ts

答案 1 :(得分:-1)

你的问题在那里:

<select [(ngModel)]="carValue" name="carName">

从您的选择中取消绑定carValue

<强> Here is an example on how to do it