0

我有以下代码:

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

我正在尝试获取令牌并使其看起来像"Bearer " + token.

根据https://akveo.github.io/nebular/docs/auth/nbauthservice#nbauthservice,NbAuthService 为令牌返回一个 Observable,但我不知道如何在听完 Observable 后返回该值。

我尝试了不同的东西,但无法理解 Observables 的概念。

有人可以帮忙吗?

4

1 回答 1

1

您想首先获取 AuthToken,然后进行第二次调用。为此,您可能需要map响应,然后Observable从其中返回实际值。但是因为这会给你一个Observable<Observable<PlatformInterface[]>>你可以使用的flatMap

试试这个:

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}`
            })
          });
      }));
  }
}
于 2018-10-05T11:06:10.443 回答