[英]Angular 4: outputing data with *ngFor not working
我正在使用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>
這是日志:
我想這個問題與地圖有關? 但是,如果我嘗試繪制響應圖,則該單詞會帶有下划線。 有人可以幫我嗎? 謝謝
更改
<img mat-card-image src="{{ spaceScreen.img }}">
至
<img mat-card-image [src]="spaceScreen.img">
在angular 2+中,您應該更喜歡綁定到屬性,而不是使用字符串插值設置它們。
this.spaceScreens = data['results'];
應該成為
this.spaceScreens = data['screenshots'];
匹配您的json格式。
嘗試使用安全操作員?
<img mat-card-image [src]="spaceScreen?.img">
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.