Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular - Property 'data' does not exist on type 'Object'

Tags:

angular

I am new to angular. I am trying to get data from a json file. but getting error Property 'data' does not exist on type 'Object'. Please review my code

Serivce.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

import { Car } from './car';

@Injectable({
  providedIn: 'root'
})
export class AddressService {

  constructor(private http: HttpClient) { }

  getCarsSmall() {
    return this.http.get('./cars-small.json')
                .toPromise()
                .then(res => <Car[]> res.data)
                .then(data => { return data; });
}
}

.json file

  {
    "data": [
        {"brand": "Volkswagen", "year": 2012, "color": "White", "vin": "dsaf"},
        {"brand": "Audi", "year": 2011, "color": "Black", "vin": "gwregre345"},
        {"brand": "Renault", "year": 2005, "color": "Gray", "vin": "h354htr"},
        {"brand": "BMW", "year": 2003, "color": "Blue", "vin": "j6w54qgh"},
        {"brand": "Mercedes", "year": 1995, "color": "White", "vin": "hrtwy34"},
        {"brand": "Volvo", "year": 2005, "color": "Black", "vin": "jejtyj"},
        {"brand": "Honda", "year": 2012, "color": "Yellow", "vin": "g43gr"},
        {"brand": "Jaguar", "year": 2013, "color": "White", "vin": "greg34"},
        {"brand": "Ford", "year": 2000, "color": "Black", "vin": "h54hw5"},
        {"brand": "Fiat", "year": 2013, "color": "Red", "vin": "245t2s"}
    ]
}
like image 452
Varma GRK Avatar asked Mar 18 '26 12:03

Varma GRK


1 Answers

You are getting this error because when you navigate to your page, you are trying to render data variable before your service response.

And my prediction is that you are not using *ngIf clause on you template side,

Try this approach,

<ul *ngIf="data">
   <li *ngFor="let item of data">
     {{item.brand}}
   </li>
</ul>

For your service side, you don't need second .then block,

  getCarsSmall() {
    return <Car[]>this.http.get('./cars-small.json')
      .toPromise()
      .then(data => { return data; });
  }
like image 153
rcanpahali Avatar answered Mar 21 '26 09:03

rcanpahali