Rx Subscribe OnComplete fires but cannot use the data

北城以北 提交于 2019-12-12 02:12:45

问题


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);
}

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 ) }
        );
}

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?

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.

cheers


回答1:


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

In addition to appearances there are actual semantic differences between () => {} and function() {}

Read here: https://developer.mozilla.org/en-US/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.

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

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



来源:https://stackoverflow.com/questions/39228150/rx-subscribe-oncomplete-fires-but-cannot-use-the-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!