【发布时间】:2020-02-17 22:15:59
【问题描述】:
我需要使用我在.subscribe 中获得的属性来更新 HTML。我知道 .subscribe 是异步的,因此在解析之前该值是未定义的,但我怎样才能让它等到它有值?目前我只得到 undefined 的对象属性。
这是我调用 API 来获取数据的服务方法:
fetchCustomers(name: string) Observable<Customer[]> {
return this.http.get<Customer>('MY URL')
}
以及我订阅它的组件:
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
})
}
但是当我调用 this.customer 方法时仍然未定义。我需要 data 的属性来呈现我的 HTML 文件,如下所示:
<tr> {{ customer.companyName }} </tr>
<tr> {{ customer.fullName }} </tr>
<tr> {{ customer.Email }} </tr>
我怎样才能让这条线this.customer = data 等到Observable 得到解决?我也尝试过this.customer = JSON.parse(JSON.stringify(data)),正如另一个帖子中所建议的那样,但它不起作用。
【问题讨论】:
-
那一行已经等到可观察对象被解析;这就是传递回调的全部意义所在。这是没有的模板的第一个渲染。要么使用安全导航,要么使用 ngIf 有条件地渲染它,要么向模板公开一个 observable 并使用 AsyncPipe。
-
感谢各位的回答。我目前无法访问代码。一旦我回到它,我会尝试它们
-
那你为什么现在问这个问题?
-
因为我在工作中做不到
-
@Peyman Kheiri - Salam Peyman ,Customer 是接口还是类?
标签: angular typescript observable