1

So I'm coming from an AngularJS background while learning Angular 5, I still can't wrap my head around observables.

I'm trying to write an HTTP interceptor for my authentication service. However when I try to get a value from the localstorage service (or any observable at this point) I'm not quite sure how to properly return the next.handle(req) method from the observable after getting the data (using subscribe?)

Here's my current code (which does not work):

@Injectable()
export class AuthinterceptorService implements HttpInterceptor {

  constructor(private storage: LocalStorage) { }

  intercept(req: HttpRequest<any>, next: HttpHandler):Observable<HttpEvent<any>> {
    return this.storage.getItem('authToken').subscribe(res => {
      return next.handle(req);
    });
  }    

}

Notice I'm not doing anything with the data, simply trying to return the Observable> object from within my async call

Thanks in advance for your help

martin
  • 93,354
  • 25
  • 191
  • 226

1 Answers1

1

Returning an Observable inside subscribe won't do anything. You need to merge it into the chain. For example like this:

return this.storage.getItem('authToken')
  .mergeMap(res => next.handle(req));
martin
  • 93,354
  • 25
  • 191
  • 226
  • Thannks Martin, this actually worked. I'm still not quite sure what I'm doing with this so I'm going to do some more reading. I was also able to perform the same functionality with something like this: return this.storage.getItem('authToken') .switchMap(r => { return next.handle.req(); }); – Rodolfo Gongora Jun 04 '18 at 21:34