从Angular2 / Typescript中的rxJs复制响应数据

时间:2016-06-08 09:37:59

标签: javascript typescript angular rxjs

我在使用TypeScript应用程序的Angular2中使用来自rxJS的Observable。我想获取http获取响应数据的副本。

服务:

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()的末尾复制一份,那么它是未定义的。

2 个答案:

答案 0 :(得分:1)

我认为你的问题与observables的异步方面有关。在getSizes方法结束时,数据尚未存在。它们将在订阅回调中提供:

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

如果要从getSizes方法返回值,则需要返回一个observable并让方法调用者订阅它:

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

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

答案 1 :(得分: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
}