Search code examples
angulartypescriptobservablengx-admin

Accessing value of an Observable


I have the following code:

// Service
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { NbAuthService, NbAuthJWTToken } from '@nebular/auth';

interface PlatformInterface {
  id: number;
  name: string;
}

@Injectable()
export class PlatformService {

  data = [];

  constructor(
    private authService: NbAuthService,
    private http: HttpClient) { }

  getData() {
    console.log(this.authService.getToken()); // This is Observable
    return this.http.get<PlatformInterface[]>(
      'http://app-backend.test/app/platforms',
      {
        headers: new HttpHeaders({
          'Content-Type': 'application/json',
          'Authorization': 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9ldmVyZ2FtZS1iYWNrZW5kLnRlc3RcL2F1dGhcL3NpZ25pbiIsImlhdCI6MTUzODczNDc2MywiZXhwIjoxNTM4ODIxMTYzLCJuYmYiOjE1Mzg3MzQ3NjMsImp0aSI6InR1SnZLQlFHR0RXRmhGcWciLCJzdWIiOjEsInBydiI6Ijg3ZTBhZjFlZjlmZDE1ODEyZmRlYzk3MTUzYTE0ZTBiMDQ3NTQ2YWEifQ.nwf10QpYweuzukerwvzPBqhGMuwGC8o5yCr0zywCa_A'
        })
      }
    );
  }
}

// Component code
this.service.getData().toPromise().then(res => {
  this.source.load(res);
});

I am trying to get token and make it look like "Bearer " + token.

According to https://akveo.github.io/nebular/docs/auth/nbauthservice#nbauthservice, NbAuthService returns an Observable for the token, but I don't know how I can return the value after listening to an Observable.

I tried different things but couldn't grasp the concept of Observables.

Could anybody help?


Solution

  • You want to first get the AuthToken and then make the second call. To do this, you might want to map the response and then return the actual Observable from inside it. But since this would give you an Observable<Observable<PlatformInterface[]>> you can use flatMap

    Try this:

    import { Injectable } from '@angular/core';
    import { HttpClient, HttpHeaders } from '@angular/common/http';
    import { NbAuthService, NbAuthJWTToken } from '@nebular/auth';
    import { flatMap } from 'rxjs/operators';
    
    interface PlatformInterface {
      id: number;
      name: string;
    }
    
    @Injectable()
    export class PlatformService {
    
      data = [];
    
      constructor(
        private authService: NbAuthService,
        private http: HttpClient
      ) {}
    
      getData() {
    
        return this.authService.getToken()
          .pipe(flatMap(token => {
            return this.http.get <PlatformInterface[]>(
              'http://app-backend.test/app/platforms', {
                headers: new HttpHeaders({
                  'Content-Type': 'application/json',
                  'Authorization': `Bearer ${token}`
                })
              });
          }));
      }
    }