简体   繁体   中英

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

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"}
    ]
}

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; });
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM