我正在使用HttpClient处理这个应用程序,它从包含图像和描述的本地json文件中获取数据(图像也是本地的)我可以记录数据(在本地数组中),但是我输出有问题它在视图中。这是请求:
export class AppComponent {
spaceScreens:Array<any>;
constructor(private http:HttpClient) {
this.http.get('assets/data/data.json')
.subscribe(data => {
this.spaceScreens = data['results'];
console.log(data);
}, (err: HttpErrorResponse) => {
if (err.error instanceof Error) {
console.log('An error occurred:', err.error.message);
} else {
console.log(`Backend returned code ${err.status}, body was: ${err.error}`);
}
});
}
}
JSON:
{
"screenshots": [
{
"img": "assets/images/space1.jpg",
"description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
"liked": "0"
}, //etc
HTML:
<mat-card *ngFor="let spaceScreen of spaceScreens; let i = index" >
<img mat-card-image src="{{ spaceScreen.img }}">
<mat-card-content>
<p>{{ spaceScreen.description }}</p>
</mat-card-content>
<mat-card-actions>
<button mat-button>
<i class="material-icons md-18" >favorite</i> LIKE
</button>
<button mat-button>
<i class="material-icons md-18">delete</i> DELETE
</button>
</mat-card-actions>
</mat-card>
这是日志:
我猜这个问题与地图有关?但是,如果我尝试映射响应,我会得到带下划线的单词。有人能给我一个帮助吗?谢谢
答案 0 :(得分:1)
更改
<img mat-card-image src="{{ spaceScreen.img }}">
到
<img mat-card-image [src]="spaceScreen.img">
在角度2+中,您应该更喜欢绑定到属性,而不是使用字符串插值设置它们。
答案 1 :(得分:1)
this.spaceScreens = data['results'];
应该成为
this.spaceScreens = data['screenshots'];
匹配您的json格式。
答案 2 :(得分:1)
尝试使用safe-operator?
<img mat-card-image [src]="spaceScreen?.img">