Angular 在6小时内,每4分钟在后台执行一次服务功能

Angular 在6小时内,每4分钟在后台执行一次服务功能,angular,angular6,scheduled-tasks,angular-httpclient,background-service,Angular,Angular6,Scheduled Tasks,Angular Httpclient,Background Service,我试图在后台执行一个服务函数,每4分钟从服务器获取一次刷新令牌 @Injectable() export class RefreshTokenService { time: any; token: string; email: string; credentials: any; constructor(private http: HttpClient) { } getToken(): string { const credentials = localStorag

我试图在后台执行一个服务函数,每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));
   });
 }}
现在我在app.component.ts
ngOnInit()
内部执行
refreshToken()
,所以每次我在app中加载页面时它都会执行,并且工作正常,但我还没有找到一种在后台每4分钟调用
refreshToken()
的正确方法


我已经看过了,但似乎不起作用

您可以使用RxJS/timer实现它


最好的方法是使用
interval
switchMap
操作符

首先,从refreshToken函数返回一个observable。使用map操作符在
refreshttoken()
方法中执行所有其他操作,如转换数据、存储在localstorage中等


从'rxjs'导入{interval,pipe};
从“rxjs/operators”导入{map,switchMap};
.....
刷新令牌(令牌:字符串){
const tokenJson:any={'token':token};
返回此.http.post('/api token refresh/',tokenJson,httpOptions);
};
checkingTokenOnInterval(){
常数间隔时间=4*60*1000;
常量标记='sdfsdf';
interval(intervalTime).pipe(switchMap(()=>this.refreshToken(token))).subscribe(()=>{
//做点什么
});
}

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

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


另一种方法-捕获401错误->复制请求->刷新令牌->发送请求副本。

我是否应该在
app.component.ts
中的
ngOnInit()中调用
checkingtokennoninterval()
?是的,如果你想每4分钟调用一次刷新令牌,它确实会在
intervalTime
中设置的时段后执行,但它只执行一次,之后我给出了这个错误
error-TypeError:您在需要流的地方提供了“undefined”。您可以提供一个可观察的、承诺的、数组的或可观察的。
知道如何修复它吗?我不确定这个错误,可能rxjs代码中会有一些小的语法错误,但您可以检查一下
    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();