0

In Angular 7, I am storing a JSON Web Token (JWT) locally via @ngx-pwa/local-storage. To get and save key-value pairs, this API is asynchronous. I then have another method which retrieves the JWT and makes a HttpClient call. I cannot seem to chain and get these async methods to work.

My method to get the JWT from localstorage is as follows.

private getHttpHeaders(): Observerable<object> {
 return this.localStorage.getItem<string>('token', {schema: {type: 'string'}}).pipe(map(token => {
  return {
   headers: new HttpHeaders({
    'Content-Type': 'application/json',
    'X-Access-Token': token
   })
  };
 }));
}

My other method looks like the following.

public isLoggedIn(): Observable<boolean> {
  const url = `${this.host}/account/isloggedin`;
  return new Observable<boolean>(observer => {
    this.getHttpHeaders()
      .pipe(map(headers => {
        return this.httpClient.get<any>(url, headers)
          .pipe(map((json) => {
            observer.next(json && json.result && json.result === true);
          }));
      }));
  });
}

When I attempt to call myService.isLoggedIn() nothing happens. If I put in console.log messages, I can trace that getHttpHeaders() is called but the Observable being returned is not invoked.

Any ideas on what I'm doing wrong?

Jane Wayne
  • 8,205
  • 17
  • 75
  • 120
  • 1
    Possible duplicate of [How to properly chain rxjs 6 observables?](https://stackoverflow.com/questions/52774281/how-to-properly-chain-rxjs-6-observables) – Jota.Toledo Feb 17 '19 at 16:45
  • 1
    You need to [`flatMap`](http://reactivex.io/documentation/operators/flatmap.html) if the callback itself returns an observable. Also you shouldn't need `new Observable`, just `return this.getHttpHeaders().pipe(flatMap(headers => this.httpClient.get(url, headers)), map(json => json && json.result === true));`. – jonrsharpe Feb 17 '19 at 16:46
  • 1
    @jonrsharpe That worked! – Jane Wayne Feb 18 '19 at 20:39

0 Answers0