返回正确的Observable <response>而不是Promise本身

时间:2017-05-02 16:48:57

标签: javascript angular typescript

我正在制作HTTP请求拦截器,并且我覆盖了Http模块get方法,因此我可以自动将JWT令牌添加到标头中。

我已尝试使用以下代码,但从方法返回时出现以下错误:

  

类型Promise<Observable<Response>>不能分配给Observable<Response>类型。

即使我尝试在then()内返回它,它也会给我同样的错误。

如何获得正确的Observable<Response>并将其退回?

// ...

@Injectable()
export class AdalHttp extends Http {
  constructor(backend: ConnectionBackend, defaultOptions: RequestOptions) {
    super(backend, defaultOptions);
  }

  get(url: string, options?: RequestOptionsArgs): Observable<Response> {
    return this.getWithAdal(url, options); // <-- ERROR HERE
  }

  private getWithAdal(url: string, options?: RequestOptionsArgs): Promise<Observable<Response>> {
    return new Promise((resolve, reject) => {
      this.authenticate((authResponse) => {
        if (!options) {
          options = { headers: new Headers() };
        }

        options.headers.set('Authorization', 'Bearer ' + authResponse.accessToken);

        resolve(super.get(url, options));
      }, err => reject(err));
    });
  }

  // ...
}

1 个答案:

答案 0 :(得分:3)

get方法应返回Observable。它调用getWithAdal方法并立即返回getWithAdal返回的对象。所以getWithAdal也应该返回Observable。

使用Observable.fromPromise将promise转换为Observable,更改getWithAdal方法的签名以返回Observable

    get(url: string, options?: RequestOptionsArgs): Observable<Response> {
      return this.getWithAdal(url, options); // <-- ERROR HERE
    }

    private getWithAdal(url: string, options?: RequestOptionsArgs): Observable<Response> {
      return Observable.fromPromise(new Promise((resolve, reject) => {
        // just make it simpler for the example.... keep your code here as is
        let options = {headers: new Headers()};
        options.headers.set('Authorization', 'Bearer ');
        resolve(super.get(url, options));
      }));
    }