根据角度4

时间:2017-05-05 14:00:00

标签: json angular rxjs observable angular2-observables

我在Angular 4项目中使用Observables(Rxjs库)从http获取来自api的数据,我想根据从API接收的数据显示徽标(png)

例如,当我的对象[{{foo_icon}}]收到0时,我展示了一场风暴,当它收到1时,我会显示一个云,以及它何时2我想要展示太阳

这是我的代码与我几周以来的尝试:

<p*ngFor="let user of userService.users | async"{{user.data.hosts.running.foo_icon}}</p> 

 <div *ngIf="cloud; then sun; else storm"></div>
<ng-template #sun><img class="foo-icon" src="./app/img/sun.png"/></ng-template>
<ng-template #cloud><img class="foo-icon" src="./app/img/cloud.png"/></ng-template>
<ng-template #storm><img class="foo-icon" src="./app/img/storm.png"/></ng-template>           
</div>    

(userService从可观察用户收到日期)

提前致谢

1 个答案:

答案 0 :(得分:1)

您可以直接在图像上使用ngIf。

<div *ngFor="let user of userService.users | async">
  <div *ngIf="user?.data.hosts.running.foo_icon as fooIcon">
     <img *ngIf="fooIcon === 'sun'" class="foo-icon" src="./app/img/sun.png"/>
     <img *ngIf="fooIcon === 'cloud'" class="foo-icon" src="./app/img/cloud.png"/>
     <img *ngIf="fooIcon === 'storm'" class="foo-icon" src="./app/img/storm.png"/>
  </div>
</div> 

或者你可以在src attr

中插入图标​​的引用
<div *ngFor="let user of userService.users | async">
  <img *ngIf="user?.data.hosts.running.foo_icon as fooIcon" [src]="'./app/' + fooIcon + '.png'"/>
</div>