在 angular 6 后每 4 分钟在后台执行一次服务功能

Execute service function in background each 4 minutes in angular 6

我正在尝试在后台执行服务功能,每 4 分钟从服务器获取刷新令牌。

 @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));
   });
 }}

现在我正在 ngOnInit() 中的 the app.component.ts 中执行 refreshToken() ,所以每次我在应用程序中加载页面时它都会执行,并且它按预期工作,但我还没有找到在后台每 4 分钟调用一次 refreshToken() 的正确方法。

我已经看过这个但它似乎不起作用...

您可以使用 RxJS/timer https://rxjs-dev.firebaseapp.com/api/index/function/timer

来实现
    this.refreshTokenService.refreshToken()
        .pipe
            tap(() => {
                // every 4 minutes refresh the discovery service
                const interval = 4 * 60 * 1000;
                timer(interval, interval).subscribe(() => {
                    this.refresh().subscribe();
                });
            })
        )
        .toPromise();

最好的方法是使用 intervalswitchMap 运算符。

首先,return 来自 refreshToken 函数的可观察对象。使用地图运算符在 refreshToken() 方法中执行所有其他操作,如转换数据、存储在本地存储等。


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 
     });
}

使用 checkingTokenOnInterval() 每 4 分钟调用一次 refreshToken。

注意在使用旧的有效令牌刷新令牌请求后立即发送的请求。我建议使用拦截器并将所有在 refreshToken 之后发送的请求排队。等到refreshToken来了再发送队列请求。

另一种方式 - 捕获 401 错误 -> 复制请求 -> refreshToken -> 发送请求副本。