Angular 导致变量未定义的可观察对象的异步行为
我在Angular2中创建了一个服务,负责对java服务进行REST调用,并使用HTTP Observable获取产品数组Angular 导致变量未定义的可观察对象的异步行为,angular,asynchronous,observable,angular2-services,angular2-components,Angular,Asynchronous,Observable,Angular2 Services,Angular2 Components,我在Angular2中创建了一个服务,负责对java服务进行REST调用,并使用HTTP Observable获取产品数组 getAll(): Observable<Product[]>{ let data$ = this.http .get(`${this.baseUrl}/productdata`, {headers: this.getHeaders()}) .map(mapData) .catch(handleError)
getAll(): Observable<Product[]>{
let data$ = this.http
.get(`${this.baseUrl}/productdata`, {headers: this.getHeaders()})
.map(mapData)
.catch(handleError);
console.log(' object array:' , data$)
return data$;
}
但OnInit方法中的最后一个操作导致product未定义,因为可观察对象的异步行为。类似地,我无法使用product的属性在HTML组件中进行插值。
我希望提取是自动的。你能给我一个方法吗 您的代码:
this.product = this.products[0];
在定义之前正在执行。将其移动到“成功”功能中
this.productService
.getAll()
.subscribe(
/* happy path */ p => {
this.products = p;
this.product = this.products[0];
},
/* error path */ e => this.errorMessage = e,
/* onComplete */ () => this.isLoading = false
);
实际上,您已经回答了自己的问题-因为它是异步的,所以您对
this.product=…
的调用会立即被调用,而可观察对象需要一些时间才能返回。解决方案很简单:
ngOnInit() {
this.productService
.getAll()
.subscribe(
/* happy path */ p => {
this.products = p;
this.product = this.products[0];
},
/* error path */ e => this.errorMessage = e,
/* onComplete */ () => this.isLoading = false);
}
将集合包含在observable回调中。因为您正在使用observable,所以您可以利用observable的所有方法,例如您已经在使用的.map()函数
this.productService
.getAll()
.map(products => products[0])
.subscribe(
/* happy path */ product => this.product = product,
/* error path */ e => this.errorMessage = e,
/* onComplete */ () => this.isLoading = false
);
非常感谢。“还有一件事,我们能在快乐的道路中嵌套一些逻辑吗?”ShubhashishMishra绝对!在可观察对象的回调中,您可以做任何您想做的事情。请记住,它是异步发生的,所以它发生在服务返回时,而不是立即返回。感谢您提供的解决方案。
this.productService
.getAll()
.map(products => products[0])
.subscribe(
/* happy path */ product => this.product = product,
/* error path */ e => this.errorMessage = e,
/* onComplete */ () => this.isLoading = false
);