Rx订阅OnComplete触发,但无法使用数据 [英] Rx Subscribe OnComplete fires but cannot use the data

查看:122
本文介绍了Rx订阅OnComplete触发,但无法使用数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个产品服务,其方法可以从json数据中返回Observable.

I have a product service with a method that returns an Observable from json data.

product.service.ts ....

getProducts(): Observable<IProductData[]> {
    return this._http.get(this._productUrl)
        .map((response: Response) => <IProductData[]> response.json())
        .catch(this.handleError);
}

在我的组件中,我预订了服务并调用getProducts()方法,返回Observable IProductData [].

In my component I subscribe to the serivce and call the getProducts() method returning the Observable IProductData[].

mycomponent.ts ..

productData: IProductData[];

ngOnInit(): void {

    this._productService.getProductsObservable()
        .subscribe(
                productData => this.productData = <IProductData[]>productData,
                error =>  this.errorMessage = <any>error,
                function() { console.log(this.productData ) }
        );
}

当我查看 onCompleted 控制台时,日志 this.productData 未定义!

When I review the onCompleted console.log this.productData is undefined!

我想使用此数据来设置组件中的字段.我何时/如何确定已返回数据?

I want to use this data to setup the fields in my component. When/how can I be sure that the data has been returned?

如果我在按钮单击事件中输出了 this.productData ,但数据已填充,但我想在init上进行.

If I output this.productData on a button click event the data has been populated, but I want to do this on init.

任何建议都将不胜感激.

Any suggestions or advice would be much appreciated.

欢呼

推荐答案

您未在最后一个块中使用箭头功能,因此您的this对于所传入的complete函数而言是本地的.

You are not using an arrow function in the final block so your this is local to the complete function that you pass in.

除了外观,() => {}function() {}

在此处阅读: https://developer.mozilla .org/zh-CN/docs/Web/JavaScript/Reference/Functions/Arrow_functions

...直到箭头函数,每个新函数都定义了自己的此值(对于构造函数,是新对象,在严格模式函数调用中未定义,如果该函数被称为对象方法",则为上下文对象,等等.).事实证明,这很讨厌面向对象的编程风格.

...Until arrow functions, every new function defined its own this value (a new object in case of a constructor, undefined in strict mode function calls, the context object if the function is called as an "object method", etc.). This proved to be annoying with an object-oriented style of programming.

在ECMAScript 3/5中,通过将其中的值分配给可以关闭的变量来解决此问题.

In ECMAScript 3/5, this issue was fixed by assigning the value in this to a variable that could be closed over.

箭头函数不会创建它自己的上下文.相反,它捕获了封闭上下文的this值...

An arrow function does not create its own this context; rather, it captures the this value of the enclosing context...

这篇关于Rx订阅OnComplete触发,但无法使用数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆