代码之家  ›  专栏  ›  技术社区  ›  Aris

可观察事物的价值

  •  0
  • Aris  · 技术社区  · 6 年前

    我有以下代码:

    // 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

    我尝试了不同的方法,但不能理解可观察的概念。

    有人能帮忙吗?

    1 回复  |  直到 6 年前
        1
  •  1
  •   SiddAjmera    6 年前

    您希望首先获取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}`
                })
              });
          }));
      }
    }