返回promise并从中创建observable时,Typescript Angular2错误

时间:2017-05-31 16:28:51

标签: angular typescript ionic-framework ionic2

我正在尝试从storage中的离子getToken()检索令牌,而不是在refreshToken()中使用它来查看令牌是否已过期,方法是将其传递给(this.jwtHelper.isTokenExpired(this.token)返回true或false,具体取决于令牌是否已过期。我已将评论放在refreshToken()我收到以下错误

错误1:

Error: TS2345:Argument of type '(response: Response) => void' is not assignable to parameter of type '(value: Response) => void'. Types of parameters 'response' and 'value' are incompatible. Type 'Response' is not assignable to type 'Response'. Two different types with this name exist, but they are unrelated. Property 'body' is missing in type 'Response'.

错误2:

Error:(34, 46) TS2339:Property 'token' does not exist on type 'Promise<any>'.

我的代码

import {AuthHttp, JwtHelper, tokenNotExpired} from "angular2-jwt";
import {Observable} from "rxjs/Observable";
import {AuthService} from "../Services/Auth/auth.service";
import {Injectable} from "@angular/core";
import { Storage } from '@ionic/storage';
import {AlertController} from "ionic-angular";

@Injectable()
export class TokenProvider {

jwtHelper: JwtHelper = new JwtHelper();
token;

constructor(private authHttp: AuthHttp, private storage: Storage, private alertCtrl: AlertController) {
}

getToken(): Promise<any> {
  return this.storage.get('token').then(token => {
     this.token = token;
  });
}

refreshToken(): Observable<any> {

  return this.token = Observable.fromPromise(this.getToken())
    .flatMap(() => {
      if(this.jwtHelper.isTokenExpired(this.token))
      {
        return this.authHttp.get('localhost.api/refresh')
          .subscribe(   // ERROR 1 HERE
            (response: Response) => {
              this.token = response.json().token;  // ERROR 2 HERE
            },
            (error: Response) => {
              console.log(error);
            });
      }
    });
}

2 个答案:

答案 0 :(得分:8)

您没有在代码中导入Response。编译器可能会对使用哪个Response感到困惑,因为您的打字中可能有多个定义:

import { Response } from '@angular/http';

此外,您没有在flatMap内返回observable。您将返回Subscription。像这样返回原始的可观察量:

refreshToken(): Observable <any> {

    let observable = Observable.fromPromise(this.getToken())
     .filter(() => this.jwtHelper.isTokenExpired(this.token))
     .flatMap(() =>  this.authHttp.get('localhost.api/refresh'));
    observable.subscribe((response: Response) => {
            this.token = response.json().token;
        }, (error: Response) => {
            console.log(error);
        });
    return observable;
}

答案 1 :(得分:0)

refreshToken函数不正确

  • 您不得在RxJS
  • 内订阅运营商
  • 获取返回Observable(或在您的情况下似乎承诺)

尝试以下方法:

refreshToken(): Observable<any> {    
  return this.token = Observable.fromPromise(this.getToken())
    .flatMap(() => {
      if(this.jwtHelper.isTokenExpired(this.token))
      {
        return this.authHttp.get('localhost.api/refresh')
      }
    })
    .catch(() => console.log(error))
    .map(response: Response => response.json())
    .subscribe(value => {
      this.token = value.token
    })
}