2016-06-08 70 views
2

我使用TypeScript应用程序中的Angular2中的rxJS使用Observable。我想获取http获取响应数据的副本。在Angular2/Typescript中复制rxJs中的响应数据

服务:

getSizes(sku: number): Observable<SizeList[]> { 
     let api = this.host + this.routes.sizes + sku; 
     return this._http.get(api) 
       .map((response: Response) => <SizeList[]>response.json()) 
       .catch(this.handleError); 
} 

组件:

getSizes() { 
     this._productService.getSizes(this.productColour) 
       .subscribe(
       sizes => this.sizes = sizes, 
       error => this.errorMessage = <any>error); 
} 

我如何可以采取this.sizes的副本?如果我尝试在我的组件getSizes()的末尾复制副本,则它是未定义的。

回答

1

我认为你的问题与observables的异步方面有关。在getSizes方法结束时,数据还在那里。他们将提供内的订阅回调:如果你想从getSizes方法返回值

getSizes() { 
    this._productService.getSizes(this.productColour) 
      .subscribe(
      sizes => { 
       this.sizes = sizes; 
       console.log(this.sizes); // <------ 
      }, 
      error => this.errorMessage = <any>error); 
} 

,你需要返回可观察到的,并让在其上的方法调用者订阅:

getSizes() { 
    return this._productService.getSizes(this.productColour) 
      .catch(error => this.errorMessage = <any>error); 
} 

someOtherMethod() { 
    this.getSizes().subscribe(sizes => this.sizes = sizes); 
} 
+0

你是正确的 - 它现在用你的第一个代码块例如工作。我不知道我可以使用{}来保存多个表达式。谢谢。 –

1

这是因为HTTP请求是在JS/Angular 2中异步制作的,因此getSizes()方法末尾的逻辑可能在方法this._productService.getSizes(...)完成加载内容之前运行。

因此,应该把你的逻辑在subscribe()方法是这样的:

getSizes() { 
     this._productService.getSizes(this.productColour) 
       .subscribe(
       sizes => { 
        this.sizes = sizes 
        // more logic here 
       }, 
       error => this.errorMessage = <any>error); 

     // code here gets executed before the subscribe() method gets called 
}