如何从localStorage或Angular2中的其他观察者作为观察者返回?

时间:2018-04-18 20:22:53

标签: angular local-storage observers angular2-localstorage

这是我的“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中,在此之后发生了一些错误,我无法弄清楚是什么问题。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

尝试在订阅

下添加一个return语句
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()