我是 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/