我在使緩存更簡單時遇到問題。我認爲有一個更好的方法來做到這一點。我的問題是我必須在每個get()函數中執行「緩存」代碼,這會導致代碼更長。任何人都可以幫助如何做到這一點最好的方式?謝謝。以下是我的代碼。我在代碼中做的是我在我的news.service.ts中使用get()函數從http獲取數據,並在我的新聞列表中訂閱它。從Angular 4中的HttpClient緩存數據
news.service.ts
getAllNews() {
if(this.newslist != null) {
return Observable.of(this.newslist);
}
else {
return this.httpClient
.get('http://sample.com/news')
.map((response => response))
.do(newslist => this.newslist = newslist)
.catch(e => {
if (e.status === 401) {
return Observable.throw('Unauthorized');
}
});
}
}
新聞list.service.ts
this.subscription = this.newsService.getAllNews()
.subscribe(
(data:any) => {
console.log(data);
this.newslists = data.data.data;
},
error => {
this.authService.logout()
this.router.navigate(['signin']);
});
}
我看不出有什麼問題... – Leo
@Leo。噢好吧,我會每次使用get()函數時使用它?那將是最好的解決方案? – Joseph
你的緩存究竟是什麼? 'newslists'? – Leo