[英]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.