繁体   English   中英

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

[英]Angular - Property 'data' does not exist on type 'Object'

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

服务

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块,

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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