I am attempting to retrieve a token from ionics storage
in getToken()
and than use it in refreshToken()
to see if the token is expired by passing it to (this.jwtHelper.isTokenExpired(this.token)
which returns a true or false depending on if the token is expired or not. I have put comments in refreshToken()
where I am getting the following errors
Error 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'.
Error 2:
Error:(34, 46) TS2339:Property 'token' does not exist on type 'Promise<any>'.
My code
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);
});
}
});
}
You are not importing Response
in your code. The compiler probably got confused on which Response
to use as there may be multiple definitions in your typings :
import { Response } from '@angular/http';
Also, you are not returning the observable inside flatMap
. You are returning the Subscription
. Return the original observable like this:
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With