I'm trying to execute a service function in the background that gets the refresh token from the server each 4 minutes.
@Injectable()
export class RefreshTokenService {
time: any;
token: string;
email: string;
credentials: any;
constructor(private http: HttpClient) {
}
getToken(): string {
const credentials = localStorage.getItem('credentials');
if (credentials) {
const parsedCredentials = JSON.parse(credentials);
const token = parsedCredentials.token;
return token;
}
return null;
}
refreshToken(token: string) {
const tokenJson: any = {'token': token};
this.http.post('/api-token-refresh/', tokenJson, httpOptions).subscribe(response => {
const data = JSON.parse(JSON.stringify(response));
this.credentials = JSON.parse(localStorage.getItem('credentials'));
this.credentials.token = data.token;
localStorage.setItem('credentials', JSON.stringify(this.credentials));
});
}}
Now i'm executing the refreshToken()
in the app.component.ts
inside ngOnInit()
, so it executes every time i load a page in the app, and it works as expected, but i haven't found a proper way to call the refreshToken()
each 4 minutes in the background.
i already looked at this but it seem not to work... How to call function every 2 mins in angular2?
The best way is to use interval
and switchMap
operator.
First, return an observable from the refreshToken function. Use map operator to do all other stuff like transforming data, storing in localstorage etc in refreshToken()
method.
import { interval, pipe } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';
.....
refreshToken(token: string) {
const tokenJson: any = {'token': token};
return this.http.post('/api-token-refresh/', tokenJson, httpOptions);
};
checkingTokenOnInterval(){
const intervalTime = 4*60*1000;
const token = 'sdfsdf';
interval(intervalTime).pipe(switchMap(() => this.refreshToken(token))).subscribe(()=>{
//do something
});
}
Use checkingTokenOnInterval()
for calling refreshToken call on every 4 minutes.