我正在尝试在我的服务中实现HTTP请求的缓存,这是我的代码片段:
//...
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/publishReplay';
//...
@Injectable()
export class FundsService {
/**
* @var {String} URL of funds api
*/
private baseUrl = 'http://budget.vagrant/api/funds';
/**
* @var {Array} Cache of last getFunds request
*/
private funds : Observable<any> = null;
constructor(
private http: Http,
private router : Router,
private authenticationService: AuthenticationService) {
}
/**
* Fetch all existing comments
* @param {boolean} useCache Will use the service's cache array when true
*/
getFunds(useCache : boolean = true) : Observable<Fund[]> {
// add authorization header with jwt token
let headers = new Headers({
'Authorization': 'Bearer ' + this.authenticationService.getToken()
});
let options = new RequestOptions({ headers: headers });
console.log("this.funds = ", this.funds) // <-- every time, null
if (this.funds === null) {
this.funds = this.http.get(this.baseUrl, options)
.map((res:Response) => res.json())
.do(funds => console.log('fetched funds', funds))
.publishReplay(1)
.refCount();
}
console.log("this.funds = ", this.funds) // <-- every time, has value from http call - but subsequent calls it'll be null again
return this.funds;
}
//...
我一直在关注本教程btw - http://www.syntaxsuccess.com/viewarticle/caching-with-rxjs-observables-in-angular-2.0
我无法理解为什么this.funds每次都重置为null。我没有刷新浏览器,只是使用Angular Router来导航“pages”(组件/模板),我假设每次都会将FundsService注入到每个新组件中,所以当我重新加载这个组件时,它将具有相同的单例实例。之前,对吗?那么this.funds将从之前的http调用设置,而不是重新初始化为null。
以下是使用该服务的组件:
export class FundsListComponent implements OnInit {
constructor(
private fundsService: FundsService,
private loadingService : LoadingService) { }
funds: Fund[];
/**
* Initialize the directive/component after Angular first displays the data-bound
* properties and sets the directive/component's input properties.
* Called once, after the first ngOnChanges().
*/
ngOnInit() : void {
this.fundsService.getFunds()
.subscribe(
funds => {
return this.funds = funds
},
error => console.log(error)
);
}