角度-属性“数据”在类型“对象”上不存在

时间:2019-03-07 07:05:16

标签: angular

我是新手。我正在尝试从json文件获取数据。但出现错误属性“数据”在类型“对象”上不存在。 请查看我的代码

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文件

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

1 个答案:

答案 0 :(得分:1)

收到此错误的原因是,当您导航到页面时,您尝试在服务响应之前呈现data变量。

我的预测是,您不会在模板端使用*ngIf子句,

尝试这种方法,

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

对于服务方面,您不需要第二个.then块,

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