Ianbara Ianbara - 4 months ago 24
JSON Question

Rx Subscribe OnComplete fires but cannot use the data

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


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

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

mycomponent.ts ..

productData: IProductData[];

ngOnInit(): void {

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.



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...