无法在Angular中显示来自JSON API的图像

问题描述 投票:0回答:2

JSON API

teams": [

    {
        "logo": "/wp-content/themes/squiggle/assets/images/Adelaide.jpg",
        "abbrev": "ADE",
        "name": "Adelaide",
        "id": 1
    },

component.ts

  teams = [];

  responseData: any

constructor(private http: HttpClient) { }

ngOnInit(): void {
    this.http.get("https://api.squiggle.com.au/?q=teams").subscribe((res: any) => {
      this.responseData = JSON.parse(JSON.stringify(res))["teams"];
    },
      err => {
        console.log(err);
      },
      () => {
        console.log(this.responseData);
      }
    )
  }

HTML文件

 <tr *ngFor="let team of responseData">
          <td>{{team.id}}</td>
          <td>{{team.abbrev}}</td>
          <td><img [src]="{{team.logo}}" alt="image"</td>
          <td>{{team.name}}</td>
 </tr>

HttpClient运行正常,除图像外均显示完美。图片显示为“ /wp-content/themes/squiggle/assets/images/Adelaide.jpg”。我尝试将img标签与src []结合使用,但似乎无法解决。

json angular httpclient angular-httpclient jsonobjectrequest
2个回答
0
投票

我不确定是这样,但是您不应该使用“ []”和“ {{}}”尝试为[src] =“ team.logo”

切换[src] =“ {{team.logo}}”“

0
投票

似乎徽标位于域https://squiggle.com.au下,而API位于https://api.squiggle.com.au/下。因此,您可能必须手动将数组的每个元素的域串联起来。我还使用RxJS pipemap修改了数据提取。尝试以下操作

IMG_BASE_URL = 'https://squiggle.com.au';

ngOnInit() {
  this.http.get("https://api.squiggle.com.au/?q=teams")
    .pipe(map(teams => {
      const result = teams['teams'];
      result.map(team => team['logo'] = this.IMG_BASE_URL + team['logo'] );
      return result;
    }))
    .subscribe(
      res => { this.responseData = res; },
      err => { console.log(err); },
      () => { console.log(this.responseData); }
    );
}

此外,绑定到img的URL应该使用数据绑定语法[src]="team.logo"或数据插值语法src="{{team.logo}}"。不应将它们混在一起,请注意方括号。

模板

<tr *ngFor="let team of responseData">
  <td>{{team.id}}</td>
  <td>{{team.abbrev}}</td>
  <td><img [src]="team.logo" alt="image"></td>
  <td>{{team.name}}</td>
</tr>
© www.soinside.com 2019 - 2024. All rights reserved.