我正在尝试从 ionicsstorage
中检索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);
});
}
});
}
您没有在代码中导入Response
。编译器可能对使用哪个Response
感到困惑,因为您的键入中可能有多个定义:
import { Response } from '@angular/http';
此外,您不会返回flatMap
内部的可观察量。您正在返回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;
}
refreshToken 函数不正确
- 您不得在 RxJS 中的运算符内订阅
- 获取返回一个可观察的(或在你的情况下看起来的承诺)
请尝试以下操作:
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
})
}