遵循本课程https://www.pluralsight.com/courses/angular-2-getting-started和 github 材料product.service在该课程中试图避免每次单击链接时调用 http.get() 请求。我认为每次加载文件而不是将其作为对象保存在内存中是一种很大的浪费。
尝试替换此代码:
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);
}
有了这个:
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._observable
如果欠精细 ,则永远不应调用此行this._observable=this._http.get(this._productUrl)
但它被称为!!!!
在 chrome 控制台中:
_observable before: [object Object]
product.service.ts:25 _observable after: [object Object]
product.service.ts:20 All inside observable:...
最后一行不应该出现!