我收到此錯誤訊息..
錯誤型別錯誤:無法
在 Object.next (customers.service.ts:16:38) 讀取未定義的屬性(讀取“geoCoord”)
如果我給“lon”和“lat”變數一個固定的值,比如 51.1634 和 10.4477,這個函式就可以作業。所以我想問題出在get請求或我定位json資料的方式上。有人可以幫我嗎?
錯誤發生在這一行。為什么我不能訪問這些值?
const lon = c.customerAdress.geoCoord.longitudeCoord;
const lat = c.customerAdress.geoCoord.latitudeCoord;
我的服務看起來像這樣
export class CustomersService {
customers: string = '../../assets/data/customerdata.json';
constructor(private http: HttpClient) {}
makeCustomerMarkers(map: L.Map): void {
this.http.get(this.customers).subscribe((res: any) => {
for (const c of res.customerArray) {
const lon = c.customerAdress.geoCoord.longitudeCoord;
const lat = c.customerAdress.geoCoord.latitudeCoord;
const marker = L.marker([lat, lon]);
marker.addTo(map);
}
});
}
}
這是我呼叫服務的組件
ngAfterViewInit(): void {
this.initMap();
this.customersService.makeCustomerMarkers(this.map);
}
這是我的資料
{
"customerArray": [
{
"customerAddress": {
"country": "Deutschland",
"geoCoord": {
"longitudeCoord": 10.4477,
"latitudeCoord": 51.1634
}
},
"phone": "0145221551",
"eMail": "[email protected]",
"homepage": "www.google.de",
},
{
"customerAddress": {
"country": "Deutschland",
"geoCoord": {
"longitudeCoord": 10.4477,
"latitudeCoord": 51.1634
}
},
"phone": "0145221551",
"eMail": "[email protected]",
"homepage": "www.google.de",
},
{
"customerAddress": {
"country": "Deutschland",
"geoCoord": {
"longitudeCoord": 10.4477,
"latitudeCoord": 51.1634
}
},
"phone": "0145221551",
"eMail": "[email protected]",
"homepage": "www.google.de",
}
]
}
uj5u.com熱心網友回復:
使用如下安全遍歷運算子?。
const lon = c?.customerAdress?.geoCoord?.longitudeCoord;
const lat = c?.customerAdress?.geoCoord?.latitudeCoord;
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/431285.html
上一篇:在一個組件中創建多個表單
下一篇:按下確認按鈕后,模態應該消失
