Angular 2/4从当时返回一个observable

时间:2017-11-13 09:28:04

标签: javascript angular ionic-framework observable ionic3

我正在为离子3 app编写一个http拦截器。拦截器从本地存储中获取一个jwt并将其添加到请求头。问题是获取令牌的方法返回一个promise,这意味着拦截器只有在promise完成后才能修改请求。但是拦截器需要返回一个Observable> (我对角2/4很新,所以我不确定这是否必要。)这是我到目前为止所做的事情

import { Injectable } from '@angular/core';
import { Storage } from '@ionic/storage';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor
} from '@angular/common/http';
import { AuthService } from './auth.service';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class TokenInterceptor implements HttpInterceptor {

  constructor(public auth: AuthService, private storage: Storage) {}

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    var token = this.storage.get('token').then((value) => {
        const dupReq = request.clone({ headers: request.headers.set('x-access-token', value) });
        return next.handle(dupReq);  // i need the intercept() function to return this  
    });
  }
}

在环顾四周之后,我明白我可以使用Observable.fromPromise()来解决这个问题,但我不知道该怎么做

0 个答案:

没有答案