【问题标题】:Angular associate json value to img pathAngular 将 json 值关联到 img 路径
【发布时间】:2021-06-30 08:36:09
【问题描述】:

我必须显示来自运行良好的 api 的数据,我需要显示每个国家及其对应的标志,但我不明白如何将 json 的值与图像的路径相关联。

示例:对于

libelle:柬埔寨双格列:KH

显示:src/assets/flags/KH.jpg


libelle:法国 bigramme:FR

显示:src/assets/flags/FR.jpg

我已经尽量说清楚了。

谢谢。

json

"drapeaux": [
    {
      "id": 1,
      "mnemo": "KHM",
      "libelle": "Cambodge",
      "bigramme": "KH"
    },
    {
      "id": 2,
      "mnemo": "KHM",
      "libelle": "France",
      "bigramme": "FR"
    }
  ]
}

服务

getAll(): Observable<Ipost[]> {
    return this.http.get<Ipost[]>(this.api);
  }

components.ts

 getAllNations() {
    let resp = this.homeService.getAll();
    resp.subscribe(result => {
      this.postArray = result;
    });
  }

html

<div class="col-12">
      <mat-card>
        <div class="row">
          <div class="col-1" *ngFor="let post of postArray">
            {{post.libelle}}
            <img [src]="post.bigramme.jpg" alt="flag">
          </div>
        </div>
      </mat-card>
    </div>

【问题讨论】:

    标签: json angular typescript


    【解决方案1】:

    你有两个选择:

    选项 1:为您服务:

    getAll(): Observable<Ipost[]> {
      return this.http.get<Ipost[]>(this.api).pipe(
        map(p => ({
          ...p,
          bigramme: `src/assets/flags/${p.bigramme}.jpg`
        }))
      )
    }
    

    然后是你的组件的 html:

    <div class="col-12">
      <mat-card>
        <div class="row">
          <div class="col-1" *ngFor="let post of postArray">
            {{post.libelle}}
            <img [src]="post.bigramme" alt="flag">
          </div>
        </div>
      </mat-card>
    </div>
    

    选项 2:或者您可以只更改组件的 html:

    <div class="col-12">
      <mat-card>
        <div class="row">
          <div class="col-1" *ngFor="let post of postArray">
            {{post.libelle}}
            <img src="src/assets/flags/{{ post.bigramme }}.jpg" alt="flag">
          </div>
        </div>
      </mat-card>
    </div>
    

    【讨论】:

    • 我想象了一个非常复杂的代码可以做,但它很简单。非常感谢
    猜你喜欢
    • 2016-03-28
    • 2016-07-17
    • 1970-01-01
    • 1970-01-01
    • 2016-04-30
    • 2015-07-14
    • 2014-11-28
    • 2022-01-26
    • 2019-09-26
    相关资源
    最近更新 更多