Here is my problem. A user types “AB”, the token is expired, the user types “C” and a call is made to refreshToken()
but I get a token_not_provided
error, user types “D” and it works fine because the token has been refreshed and stored in time.
Does anybody have any solutions for this? Can I delay the call with a timer if the token is expired? Do I need to fork the calls so they are made in parallel?
refreshToken() {
if (this.jwtHelper.isTokenExpired(this.token)) {
this.authHttp.get('http://test.app/api/refresh?token=' + this.token)
.map(res => res.json())
.subscribe(data => {
this.setToken(data.token);
// this.storage.ready().then(() => this.storage.set('token', data.token));
console.log("in refresh");
},
err => console.log("refreshToken()", err) )
}
}
Getting the token
jwtHelper: JwtHelper = new JwtHelper();
token;
constructor(private authHttp: AuthHttp, private storage: Storage, private alertCtrl: AlertController, private http: Http) {
storage.ready().then(() => storage.get('token'))
.then(token =>
{
this.token = token;
this.checkToken(token);
});
}
searchService.ts
search(keyword): Observable<any>
{
this.auth.refreshToken();
return this.authHttp.get('http://test.app/api/search/' + keyword)
.map(
(response: Response) => {
return response.json().jobSites;
},
(error: Response) => {
console.log(error);
}
);
}
in component
onSearch(event)
{
let keyword = event.target.value;
this.searchService.search(keyword)
.subscribe(
(loc: Home[]) => this.loc = loc,
(error: Response) => {
console.log(error);
//alert("Session Expired. You must login again.");
}
)
}
app.module.ts
export function getAuthHttp(http, storage) {
return new AuthHttp(new AuthConfig({
headerPrefix: '',
noJwtError: true,
globalHeaders: [{'Accept': 'application/json', 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest'}],
tokenGetter: (() => storage.ready().then(() => storage.get('token')))
}), http);
}