D.Dave
D.Dave

Reputation: 77

Property does not exist on object - Angular

I have an object, which I want to fill and use the description property

public obj = {};
  setObj(){
    this.sp.getResourceUrl(this.results[0].resource_url).subscribe(data => {
      this.obj = data; // data has description property
    });
  }

It worked fine for a while with the following html code but somehow the error "The property description does not exists on type {}"

    <div *ngIf="obj && obj.description != ''; else notfound">
        {{obj.description}}
    </div>
    <ng-template #notfound>
        <div>
            Description not found.
        </div>
    </ng-template>

Do I have to set all properties I receive from the object I get via GET-Request? If yes, why? It worked fine before.

Upvotes: 2

Views: 5552

Answers (4)

Shlok Nangia
Shlok Nangia

Reputation: 2377

Please use the following code

<div *ngIf="obj && obj.description; else notfound">
    {{obj.description}}
</div>
<ng-template #notfound>
    <div>
        Description not found.
    </div>
</ng-template>

i.e. it will display if and only if obj and obj.description will exist otherwise notfound will be displayed

Upvotes: 2

Ashish Ranjan
Ashish Ranjan

Reputation: 12960

This is a typescript warning to you but a fine javascript code.

Yes, you should ideally define type of properties you are using in your classes, this way it helps to mitigate unseen errors which can happen during runtime. For example if you are accessing {{obj.description}} instead of {{obj.descriptions}}, typescript warns you before hand rather than you finding it at runtime that there is no description on obj

You can have an Interface or a type for these props.

Here for example, it should be:

public obj: {descriptions?: string} = {}; // add more keys if you get more keys hetre

One way to bypass your errors would be to type it as any

public obj: any = {};

Upvotes: 4

Sajeetharan
Sajeetharan

Reputation: 222572

The solution is check for null or undefined (to see whether the object exists) using safe navigation operator

 <div *ngIf="obj && obj?.description != ''; else notfound">

Also make sure you are defining the type if you already know it, or use any

 this.sp.getResourceUrl(this.results[0].resource_url).subscribe((data : any) => {
      this.obj = data; // data has description property
    });

Upvotes: 0

Majid Nayyeri
Majid Nayyeri

Reputation: 444

You are just checking for obj availability and not its description.

As this line public obj = {}; says, obj is just an empty object in the first and obj.description is undefined.

So you should first check for the description availability and then check the value or etc.

Upvotes: 1

Related Questions