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