How to bind data from HttpClient in angular 6?

Viewed 844

I'm using this method to get the data:

home.service.ts

getHomes(): Observable<HomeApi> {
    const httpOptions = {
        headers: new HttpHeaders({
            'Content-Type': 'application/x-www-form-urlencoded',
            'token': `${this.global.token}`
        })
    };
    return this.http.get<HomeApi>('url', httpOptions);
}

home.component.ts

ngOnInit() {
    this.service.getHomes().subscribe((res: HomeApi) => this.home = {
        images: res['images']
    });
}

home.component.html

<div *ngFor="let item of home.images">{{item.name}}</div>

Now item.name work great, but in console throws this error:

ERROR TypeError: Cannot read property 'images' of undefined

Here is the Sample

2 Answers

Because your getHomes call is asynchronous, Angular attempts to render the contents of home.images before it has been assigned. After this happens, home.images gets assigned in your code and triggers a change-detection cycle that ends up with your *ngFor running successfully.

One way to handle this is to use something like the following:

<div *ngIf="home">
    <div *ngFor="let item of home.images">{{item.name}}</div>
</div>

This simply ensures that home is not undefined before attempting to process the *ngFor, which will resolve your console error.

Another option is to use the safe navigation operator:

The Angular safe navigation operator (?.) is a fluent and convenient way to guard against null and undefined values in property paths.

This is as simple as adding a ? to home:

<div *ngFor="let item of home?.images">{{item.name}}</div>

You have probably not initialized home. So the first time you initialize home is here:

this.home = {
        images: res['images']
    }

Until then *ngFor looks for items in home object which is undefined until the asynchronous request is completed and home is initialized.

Try to initialize home on top of your component: e.g. home: any = {};

Check this piece, which demonstrates what it is probably happening.

Related