Pey*_*iri 1 observable typescript angular
我需要使用内部获取的属性.subscribe来更新HTML。我知道这.subscribe是异步的,因此在解析值之前是不确定的,但是如何让它等到具有该值呢?目前,我仅获得undefined对象属性。
这是我的服务方法,在这里我调用API来获取数据:
fetchCustomers(name: string) Observable<Customer[]> {
return this.http.get<Customer>('MY URL')
}
Run Code Online (Sandbox Code Playgroud)
以及我订阅的组件:
customer: any;
name: string;
ngOnInit() {
//this.name = /*code to retrieve the name*/
this.renderCustomer(this.name)
}
renderCustomer(name) {
this.testService.fetchCustomer(name).subscribe(data => {
this.customer = data
})
}
Run Code Online (Sandbox Code Playgroud)
但是当我调用该方法时this.customer仍未定义。我需要的属性data来呈现这样的HTML文件:
fetchCustomers(name: string) Observable<Customer[]> {
return this.http.get<Customer>('MY URL')
}
Run Code Online (Sandbox Code Playgroud)
我如何使这条线this.customer = data等到Observable解决?我也尝试过this.customer = JSON.parse(JSON.stringify(data))在另一个线程中建议它,但是它没有用。
您的代码看起来正确!您可以尝试使用安全的导航操作员吗?
<tr> {{ customer?.companyName }} </tr>
<tr> {{ customer?.fullName }} </tr>
<tr> {{ customer?.Email }} </tr>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
76 次 |
| 最近记录: |