简体   繁体   English

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

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

I am new to angular.我是角度的新手。 I am trying to get data from a json file.我正在尝试从 json 文件中获取数据。 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 .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"}
    ]
}

You are getting this error because when you navigate to your page, you are trying to render data variable before your service response.您收到此错误是因为当您导航到您的页面时,您正在尝试在服务响应之前呈现data变量。

And my prediction is that you are not using *ngIf clause on you template side,我的预测是您没有在模板方面使用*ngIf子句,

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,对于您的服务端,您不需要第二个.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