Angular - 类型 'data' 上不存在属性 'Object'

标签 angular

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

服务.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"}
    ]
}

最佳答案

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

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

试试这个方法,

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

对于您的服务端,您不需要第二个 .then block ,

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

关于Angular - 类型 'data' 上不存在属性 'Object',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55037889/

相关文章:

html - ion-item 内的 ion-textarea 在 IONIC 2 上不起作用

angular - 将 Angular 从 4.0.0-beta.5 升级到 4.0.0 会中断动画和单元测试

Angular 2单元测试报错Unable to get property 'preventDefault' of undefined or null reference

python - 在 Angular 4 模板中使用 django 标签?

css - 使用 templateUrl 显示带有图像的 div

html - 从迭代循环中隐藏特定内容并在隐藏面板中显示

javascript - ionic 2 : Runtime Error Uncaught (in promise): TypeError: Cannot read property 'nav' of undefined

Angular 7 : Unit test Jasmine automate window size on mobile and web

angular - 处理将 API 对象映射到 UI 模型对象的模式

angular - 如何以编程方式切换 Angular Material 扩展面板