1

这是我的“贷款类型”服务 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 中,在此之后发生错误,我无法弄清楚出了什么问题。任何的想法?

4

1 回答 1

1

尝试在订阅下添加退货声明

localStorage.setItem('loantypes', JSON.stringify(result) );
localStorage.setItem('loantypes_are_valid', '1');
return result

调用观察者的 next()

 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()
于 2018-04-18T20:40:08.597 回答