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 File
<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>
The HttpClient is working fine and display it perfectly except of the images. The image are being displayed as "/wp-content/themes/squiggle/assets/images/Adelaide.jpg". I have tried using img tag with src[] but does not seem to fix.
It appears the logos are under the domain https://squiggle.com.au
whereas the API is under https://api.squiggle.com.au/
. So you might have to manually concatenate the domain for each element of the array. I've modified the data extraction as well using RxJS pipe
and map
. Try the following
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.forEach(team => team['logo'] = this.IMG_BASE_URL + team['logo'] );
return result;
}))
.subscribe(
res => { this.responseData = res; },
err => { console.log(err); },
() => { console.log(this.responseData); }
);
}
Also the URL binding to img
should either be using data binding syntax [src]="team.logo"
or data interpolation syntax src="{{team.logo}}"
. They shouldn't be mixed together, please notice the square brackets.
Template
<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>