ngIf与img取决于从Observables Angular 4返回的数字

时间:2017-05-09 14:29:42

标签: angular typescript rxjs ngfor ngif

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

如果我的“.acknowledged”返回“1”,我试图显示图像,如果返回“0”,则不应显示任何内容......它适用于字符串但不带数字..我不是真的明白为什么......

3 个答案:

答案 0 :(得分:0)

为什么不做以下事情:

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

答案 1 :(得分:0)

映射您的Observable并创建iconId作为您可以在html中测试的数字

userService.users
.map(user= > {
   let icon = user.data.hosts.running.foo_icon;
   let iconId = icon === 'sun' ? 1 : (icon === 'cloud' ? 2 : 3);
   return Object.assign({}, user, {iconId});
 });

答案 2 :(得分:0)

你不需要Observable来做到这一点:

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

编辑:

如果您的数字代表您的照片,只需在您的TS或服务中执行地图:

public numberToName = {
  0: 'sun',
  1: 'cloud',
  2: 'storm'
}

然后你可以这样使用它:

<div *ngFor="let user of userService.users | async">
  <div *ngIf="user.data.hosts.running.foo_icon as fooIcon">
    <img
      *ngIf="numberToName(fooIcon)"
      class="foo-icon"
      [src]="'./app/img/' + numberToName(fooIcon) + '.png'"/>
  </div>
</div>