这是我的“loantype”服务get()函数:
get() {
return new Observable(observer => {
let response;
if ( localStorage.getItem('loantypes_are_valid') === '1' ) {
response = JSON.parse(localStorage.getItem('loantypes') || '[]');
} else {
response = this.getAll().subscribe(result => {
localStorage.setItem('loantypes', JSON.stringify(result) );
localStorage.setItem('loantypes_are_valid', '1');
});
}
return response;
});
}
我只想使用这样的服务:
this.loanTypes.get().subscribe(
response => this.loantypes = response,
(error: AppError) => {throw error; }
);
现在,目标是从localStorage提供数据,如果它有效,否则我需要从API服务器重新加载它,将其存储到localStorage(用于下一个请求)并将数据提供给组件。
此代码将数据存储到localStorage中,在此之后发生了一些错误,我无法弄清楚是什么问题。有什么想法吗?
答案 0 :(得分:1)
尝试在订阅
localStorage.setItem('loantypes', JSON.stringify(result) );
localStorage.setItem('loantypes_are_valid', '1');
return result
击> <击> 撞击>
调用观察者的下一个()
if () {
observer.next(JSON.parse(...))
}
else {
response = this.getAll().subscribe(result => {
localStorage.setItem('loantypes', JSON.stringify(result) );
localStorage.setItem('loantypes_are_valid', '1');
observer.next(result)
});
}
observer.complete()