Javascript 在Angular2/Typescript中从rxJs复制响应数据
我在Angular2和TypeScript应用程序中使用rxJS中的Observable。我想复制一份http get响应数据 服务:Javascript 在Angular2/Typescript中从rxJs复制响应数据,javascript,typescript,angular,rxjs,Javascript,Typescript,Angular,Rxjs,我在Angular2和TypeScript应用程序中使用rxJS中的Observable。我想复制一份http get响应数据 服务: getSizes(sku:number):可观察{ 让api=this.host+this.routes.size+sku; 返回此。\u http.get(api) .map((response:response)=>response.json()) .接住(这个.把手错误); } 组成部分: getSizes(){ this.\u productServi
getSizes(sku:number):可观察{
让api=this.host+this.routes.size+sku;
返回此。\u http.get(api)
.map((response:response)=>response.json())
.接住(这个.把手错误);
}
组成部分:
getSizes(){
this.\u productService.getSizes(this.productColor)
.订阅(
大小=>this.size=大小,
error=>this.errorMessage=error);
}
我怎样才能复印这本书?如果我试图在我的组件getSizes()的末尾复制一个副本,它是未定义的。我认为您的问题与可观察对象的异步方面有关。在
getSizes
方法的末尾,数据仍然存在。它们将在订阅回调中可用:
getSizes() {
this._productService.getSizes(this.productColour)
.subscribe(
sizes => {
this.sizes = sizes;
console.log(this.sizes); // <------
},
error => this.errorMessage = <any>error);
}
这是因为HTTP请求是在JS/Angular 2中异步进行的,因此
getSizes()
方法末尾的逻辑可能在该方法完成加载内容之前运行
因此,您应该将逻辑放在subscribe()
方法中,如下所示:
getSizes(){
this.\u productService.getSizes(this.productColor)
.订阅(
大小=>{
this.size=大小
//这里有更多的逻辑
},
error=>this.errorMessage=error);
//在调用subscribe()方法之前执行此处的代码
}
您是正确的-现在使用您的第一个代码块示例即可。我不知道我可以用{}来保存多个表达式。非常感谢。
getSizes() {
return this._productService.getSizes(this.productColour)
.catch(error => this.errorMessage = <any>error);
}
someOtherMethod() {
this.getSizes().subscribe(sizes => this.sizes = sizes);
}