4

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

5
  • it seems that you are receiving back a malformed or an undefined response. what do you receive? Commented Sep 13, 2018 at 9:13
  • Can you do console.log(res) and check what is being returned? Commented Sep 13, 2018 at 9:16
  • Response is ok, becuase it's printing the data using ngFor Commented Sep 13, 2018 at 9:19
  • add if statement inside the {} to avoid the undefined values . for example, this.home = { if (res['images']) images: res['images'] } Commented Sep 13, 2018 at 9:26
  • Hi, Could you please tell us how you have instantiated home, so that we can help you further? Also please check if the field is not private. Commented Sep 13, 2018 at 9:54

2 Answers 2

5

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>
Sign up to request clarification or add additional context in comments.

2 Comments

If you make the change I suggested in my answer, your sample works without errors. Have you tried it?
in my real project dos not work but in stackBlitz it's working. the console is now without errors but not showing anything
1

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.

2 Comments

I'm using interface as type for home variable, still throws undefined
By using interface you are just defining the type of home - you still don't initialize it. You have to do something like home: HomeApi = { sliders: [] } on top of your component.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.