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

后端 未结 3 1635
北海茫月
北海茫月 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 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 = []; // code changed
        ...
        getPosts() {
            this.http.get('https://reqres.in/api/users?page=3').subscribe(res =>
            this.results = res.data); // code changed
        }
    }
    
    
    
    {{ result | json }}

    2) Use safe navigation operator

    {{ result | json }}

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

提交回复
热议问题