[英]How to display image from JSON object in Angular
我有一個頁面,我想在其中顯示不同人共享的圖像或視頻。 我無法從 rest API 獲取圖像。 API 看起來像
{
"status": "success",
"code": 200,
"response": [
{
"Id": 91,
"Media": [
{
"ImagePath": "http:/13.232.25.79:4105/files/7/7051252eae6820fd3309120d72fe2978.jpg",
"LikeCount": 0,
"Comment": ""
},
{
"ImagePath": "http:/13.232.25.79:4105/files/7/car.jpg",
"LikeCount": 0,
"Comment": ""
}
],
"CandidateId": 7,
"Message": "hello",
"CreatedAt": "2020-12-15T11:31:12.488Z",
"Candidates": {
"Id": 7,
"FirstName": "Rajesh",
"LastName": "Bhati"
}
}
],
"error": [],
"message": "Media list"
}
我試過以下代碼
我的組件.html
<div class="form-group" *ngFor="let candidateMedia of sharedMedia">
<div class="container_box">
<p>{{candidateMedia.Candidates.FirstName }}
{{candidateMedia.Candidates.LastName }} shares following post</p>
<img src="{{filteredImages(candidateMedia.Media.ImagePath)}}">
</div>
</div>
我的 componenet.ts 文件
ngOnInit() {
this.socialService.getMedia().subscribe((res: any) => {
this.sharedMedia = res.payload
})
}
filteredImages(value) {
const imageString = value.replace('13.232.25.79:4600/', '')
return imageString
}
您可以在下面查看您的代碼:
<img src="{{filteredImages(candidateMedia.Media.ImagePath)}}">
請務必檢查您的回復。 我的意思是您的 Media 是一個array
,而不是object
。 因此,如果您想獲取並顯示第一張圖像,也許您可以使用該圖像的index
,或者如果您想顯示所有圖像,請確保為該媒體添加*ngFor
。
僅適用於第一張圖片:
<img src="{{filteredImages(candidateMedia.Media[0].ImagePath)}}">
對於所有圖像:
<img *ngFor="let media of candidateMedia.Media" src="{{filteredImages(media.ImagePath)}}">
更新:添加Pipe
如果你想使用 pipe 來解析你的 imagePath,你可以使用下面的 pipe:
創建resolve-image-path.pipe.ts
並粘貼以下代碼:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'resolveImagePath'})
export class ResolveImagePath implements PipeTransform {
transform(imagePath: string): string {
const urlSplit = imagePath.split('/');
const indexOfFiles = urlSplit.indexOf('files');
return urlSplit.splice(indexOfFiles).join('/');
}
}
之后,您可以在 module.ts 中declare
module.ts
,之后,您可以調用 pipe 來解析您的圖像路徑。 例如:
<img *ngFor="let media of candidateMedia.Media" src="{{media.ImagePath | resolveImagePath}}">
現在,你可以嘗試自己的。
您必須遍歷 Media 數組以獲取相應的對象,前提是它應該包含正確的圖像 url
<div class="form-group" *ngFor="let candidateMedia of sharedMedia">
<div class="container_box">
<p>{{candidateMedia.Candidates.FirstName }}
{{candidateMedia.Candidates.LastName }} shares following post</p>
<img *ngFor="let img of candidateMedia.Media" [src]="img.ImagePath">
</div>
</div>
在您的 API 數據中,缺少一個/
。 在這種情況下
<div class="form-group" *ngFor="let candidateMedia of sharedMedia">
<div class="container_box">
<p>{{candidateMedia.Candidates.FirstName }}
{{candidateMedia.Candidates.LastName }} shares following post</p>
<img *ngFor="let img of candidateMedia.Media" src="{{filteredImages(img.ImagePath)}}">
</div>
</div>
在 ts
filteredImages(value) {
const imageString = value.replace('http:/13.232.25.79:4105', 'http://13.232.25.79:4105')
return imageString
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.