Following this course https://www.pluralsight.com/courses/angular-2-getting-started and github materials product.service in that course trying to avoid calling http.get() request every time I click the link. I think it is a big waste to load file every time instead of saving it as an object in memory.
Trying to replace this code:
getProducts(): Observable<IProduct[]> {
return this._http.get(this._productUrl)
.map((response: Response) => <IProduct[]> response.json())
.do(data => console.log('All: ' + JSON.stringify(data)))
.catch(this.handleError);
}
with this one:
public _observable: Observable<IProduct[]>;
getProducts(): Observable<IProduct[]> {
console.log('_observable before: ' + (this._observable));
if(this._observable===undefined){
console.log('_observable inside 1: ' + (this._observable));
this._observable=this._http.get(this._productUrl)
.map((response: Response) => <IProduct[]> response.json())
.do(data => console.log('All inside observable: ' + JSON.stringify(data)))
.catch(this.handleError);
console.log('_observable inside 2: ' + (this._observable));
}
console.log('_observable after: ' + (this._observable));
return this._observable;
}
this line should never be called if this._observable
is underfined this._observable=this._http.get(this._productUrl)
BUT IT IS CALLED!!!!
In a chrome console:
_observable before: [object Object]
product.service.ts:25 _observable after: [object Object]
product.service.ts:20 All inside observable:...
Last line shouldn't appear!