我在使缓存更简单时遇到问题。我认为有一个更好的方法来做到这一点。我的问题是我必须在每个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