Angular's new http client error Cannot read property 'data' of undefined

后端 未结 3 1605
北海茫月
北海茫月 2020-12-07 03:27

I am learning how to use angular\'s new http client module. I get the error Cannot read property \'data\' of undefined when I try to consume the rest api. Here\'s my app.htm

相关标签:
3条回答
  • 2020-12-07 03:54

    Cannot read property 'data' of undefined simply means that results in not defined. Put console.log or apply breakpoints and try to find out why its not getting defined. When we apply breakpoints we can find out the exact reasons why it is not getting defined. Knowing the reason is important.

    0 讨论(0)
  • 2020-12-07 04:09

    Since you are making a asynchronous request, initially results will be undefined, use a safe navigation operator to check if the results exists and then access the data

    <div *ngFor="let result of results?.data">
          {{ result | json }}
     </div>
    
    0 讨论(0)
  • 2020-12-07 04:12

    Issue is same as explained by @Sajeetharan :

    Since you are making a asynchronous request, initially results will be undefined,

    You can solve it by 2 ways :

    1) Provide some initial value from the very beginning:

    export class AppComponent implements OnInit {
        results:Array<any> = []; // code changed
        ...
        getPosts() {
            this.http.get<ItemsResponse>('https://reqres.in/api/users?page=3').subscribe(res =>
            this.results = res.data); // code changed
        }
    }
    
    
    <div *ngFor="let result of results">
       {{ result | json }}
    </div>
    

    2) Use safe navigation operator

    <div *ngFor="let result of results?.data">
        {{ result | json }}
    </div>
    

    But it's standard practice to use the second way.

    0 讨论(0)
提交回复
热议问题