简体   繁体   English

Angular 4:使用* ng输出数据不起作用

[英]Angular 4: outputing data with *ngFor not working

I'm working on this app with HttpClient, which gets data from a local json file containing images and description (the images are also local) I can log the data (in local array), but I'm having trouble outputing it in the view. 我正在使用HttpClient开发此应用程序,该程序从包含图像和描述的本地json文件中获取数据(图像也是本地的),我可以记录数据(在本地数组中),但是在将其输出时遇到了麻烦视图。 This is the request: 这是请求:

  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}`);
          }
        });
    } 

}

The JSON: 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

The HTML: 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> 

This is the log: 这是日志:

在此处输入图片说明

I guess the issue has to do with the map? 我想这个问题与地图有关? But if I try to map the response I get the word underlined. 但是,如果我尝试绘制响应图,则该单词会带有下划线。 Can someone give me a help? 有人可以帮我吗? Thank you 谢谢

change 更改

<img mat-card-image src="{{ spaceScreen.img }}">

to

<img mat-card-image [src]="spaceScreen.img">

In angular 2+ you should prefer binding to attributes rather then setting them with string interpolation. 在angular 2+中,您应该更喜欢绑定到属性,而不是使用字符串插值设置它们。

this.spaceScreens = data['results'];

should become 应该成为

this.spaceScreens = data['screenshots'];

to match your json format. 匹配您的json格式。

尝试使用安全操作员?

<img mat-card-image [src]="spaceScreen?.img">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM