在发送其他请求之前,不会重复/执行http GET

时间:2019-02-09 19:22:31

标签: angular typescript http rxjs

我在通过API的GET请求轮询某些数据时遇到问题。我想每1秒轮询一次数据,最多30秒。关键是,角度似乎正在执行请求(它正在记录响应),而实际上它并未执行向服务器的请求

我在服务中编写了以下方法:

private pollStatus(token: string, remember: boolean):Observable<any> {
  const httpOptions = {
    headers: new HttpHeaders({
      'Token': token,
      'Remember': '' + remember
    })
  };
  const url = 'auth/status';

  return this.http.get<any>(url, httpOptions).pipe(map(response => {
    console.log('polldata', response.status);
    return response;
  }));
}

public secondFactor(token: string, remember: boolean): Observable<any> {

  let pollData$ = this.pollStatus(token, remember);

  let watchdog = timer(30 * 1000);
  // this.http.post<any>('/auth/login', {}).subscribe();

  return Observable.create(subject => {
    let pollSubscription = pollData$.pipe(expand(_ => timer(1000).pipe(concatMap(_ => pollData$))), takeUntil(watchdog)).subscribe(response => {
      console.log('secondFactor', response.status);
      // some action based on the response is performed here
    });
  });
}

在组件中,我这样称呼它:

public ngOnInit(): void {
    this.authService.secondFactor(this.authyToken, true).subscribe(response => {
      console.log('response in component', response);
    });
}

在控制台中,我可以看到多次执行get请求的预订(执行了代码console.log('polldata', response.status);)。不幸的是,仅对服务器执行了一个请求(已在后端和“网络”标签上验证)。

控制台中的输出:

polldata pending
secondFactor pending
polldata pending
secondFactor pending
polldata pending
secondFactor pending
polldata pending
secondFactor pending
polldata pending
secondFactor pending

etc. etc. etc.

我在不同的浏览器(Safari和Chrome)下检查了此行为-同样的问题。

解决方法:

我发现,如果我将一些POST请求发送到我的服务器(注释行:// this.http.post<any>('/auth/login', {}).subscribe();中的secondFactor(),那么Angular将开始执行GET请求,然后再执行一次。) >

1 个答案:

答案 0 :(得分:0)

您能检查一下是否可行:

public secondFactor(token: string, remember: boolean): Observable<any> {
    let pollData$ = this.pollStatus(token, remember);

    let watchdog = timer(30 * 1000);

    return interval(1000).pipe(
        takeUntil(watchdog),
        concatMap(() => pollData$),
        tap(response => console.log('secondFactor', response.status))
    );
}