1

Here is my "loantype" service get() function:

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;
  });
}

I just want to use this service something like this:

this.loanTypes.get().subscribe(
  response => this.loantypes = response,
  (error: AppError) => {throw error; }
);

Now, the goal is to serve the datas from localStorage if it's valid, otherwise I need to reload it from the API server, store it into the localStorage (for the next requests) and serve the datas into the component.

This code store the datas into the localStorage, and after this happening something wrong and I can't figure out what is wrong. Any idea?

netdjw
  • 5,419
  • 21
  • 88
  • 162

1 Answers1

1

Try adding a return statement under subscription

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

Call the Observer's 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()
Ashish Ranjan
  • 12,760
  • 5
  • 27
  • 51