I have a method in my service which reads the token from storage and returns a promise.
getToken() {
return this.storage.get('access_token');
}
(storage.get returns a promise)
I need to modify the above method such that it first read the access token from storage and check its expiry, if its not expired return it immediately, if its expired read refresh_token from storage i.e. this.storage.get('refresh_token') which again returns a promise, after checking if its not expired, I need to make http request using Angular 2 http.post to my api which will return a new access token. Once it receive the new access token the getToken function will return.
I though the below will work, but it doesnt:
getToken() {
var promise = new Promise(function (resolve, reject) {
this.storage.get('access_token').then((accessToken) => {
//check if the token is expired
if (accessToken) {
if (!this.isExpired(accessToken)) {
resolve(accessToken);
}
else {
this.storage.get('refresh_token').then((refreshToken) => {
if (!this.isExpired(refreshToken)) {
this.http.post('/api/refresh/', { token:refreshToken })
.subscribe((data) => {
resolve(data);
});
}
else {
resolve(null);
}
});
}
} else {
resolve(null);
}
});
});
return promise;
}
Can anyone please guide, how to achieve this?