[英]How to pass Id fetched from api to angular method?
從列表中單擊商店名稱后,我希望能夠顯示商店名稱。 下面是我到目前為止的代碼,它不起作用! 我嘗試更改HTML模板,特別是(code)=“”部分。 難道我做錯了什么? 現在,它可以正常工作,但是收到“無法讀取未定義的屬性'名稱'”錯誤。
Shops.ts
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-shops',
templateUrl: './shops.component.html',
styleUrls: ['./shops.component.css']
})
export class ShopsComponent implements OnInit {
shops: any;
shop: any;
constructor(private http: HttpClient) { }
ngOnInit() {
this.getShops();
}
getShops() {
this.http.get('https://localhost:44366/api/shops').subscribe(response => {
this.shops = response;
}, error => {
console.log(error);
});
}
getShop(id: number) {
this.http.get('https://localhost:44366/api/shops/' + id).subscribe(response => {
this.shop = response;
}, error => {
console.log(error);
});
}
}
Shops.html
<ul *ngFor="let s of shops">
<li><a href="" (click)="getShop(s.id)">{{s.name}}</a></li>
<li>{{s.address}}</li>
</ul>
<p>{{shop.name}}</p>
您的shop變量在初始情況下沒有任何價值。 其未定義。 因此,您可以在ngOnInit()部分中將一些值分配給shop變量,或使用安全的導航符號(?)
{{店?。名稱}}
<ul *ngFor="let s of shops">
<li><a href="" (click)="getShop(s.id)">{{s.name}}</a></li>
<li>{{s.address}}</li>
</ul>
<p>{{shop?.name}}</p>
要檢查您的商店變量的內容,請使用此代碼
<p>{{shop | json }}
嘗試傳遞整個對象,並使用安全的導航運算符顯示從異步調用中檢索到的商店名稱
<ul *ngFor="let s of shops">
<li><a href="" (click)="getShop(s.id)">{{s.name}}</a></li>
<li>{{s.address}}</li>
</ul>
<p>{{shop?.name}}</p>
無論如何,最好創建一個Interface
來處理模板上的對象。
看到我正在接收JSON對象時,我應該已經將自己的shop變量初始化為type對象,並從ts文件開始。
shop: {};
然后,我不得不進入我的HTML模板並稍微修改代碼
<p>{{shop?.name}}</p>
看來解決此問題的正確方法是創建一個接口。 我現在將研究該解決方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.