可观察到的Angular HttpClient无法完成

时间:2019-06-05 10:30:34

标签: javascript angular rxjs observable angular-httpclient

我有以下代码:

// in a service
downloadCSV(): Observable<Blob> {
  return this.httpClient.get(`${apiUrl}/a.csv`, {responseType: 'blob'});
}
// in component
onDownloadClicked(event: MouseEvent) {
  this.downloading = true;
  this.service.downloadCSV()
    .pipe(finalize(() => this.downloading = false))
    .subscribe(
      (data: Blob) => {
        console.log(data);
      },
      (error) => {
        console.error(error);
        alert('Sorry, something wet wrong. Try again.');
      },
      () => {
        console.log('completed!');
      }
    );
}

数据已正确记录但已“完成!”没有记录,并且永远不会调用finalize。

编辑:

因此,在进一步调查中,问题似乎与添加了auth标头的拦截器有关。

如果绕过了拦截器(并且在服务器上禁用了身份验证),则可观察对象将完整无误地完成。

我不明白为什么会这样。可能与克隆请求的事实有关吗?

//interceptor code
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  let scope: string;
  // only inject tokens for the following scopes
  if (req.url.indexOf('https://graph.microsoft.com') === 0) {
    scope = 'https://graph.microsoft.com';
  }
  else if (req.url.indexOf('https://management.azure.com') === 0) {
    scope = 'https://management.azure.com';
  }
  else if (req.url.indexOf(environment.apiUrl) === 0) {
    scope = environment.appId;
  }
  if (scope) {
    return this.authService.getToken(scope).pipe(
      switchMap((token) => {
        let newReq;
        if (token) {
          const JWT = `Bearer ${token}`;
          newReq = req.clone({
            setHeaders: {
              Authorization: JWT,
            }
          });
        }
        return next.handle(newReq || req);
      })
    );
  }
  else {
    return next.handle(req);
  }
}

1 个答案:

答案 0 :(得分:1)

因此,事实证明问题出在我的身份验证服务的getToken函数中。我忘记了返回令牌后完成可观察的事!由于httpClient.get observable是通过我的getToken observable切换映射的,因此导致我在onDownloadClicked中的订阅无法完成。

// from my auth service
getToken(resource: string): Observable<string> {
  return Observable.create((observer: Observer<string>) => {
    this.context.acquireToken(resource, (error, token) => {
      if (token) {
        observer.next(token);
        observer.complete(); // this was missing
      }
      else {
        this.login();
      }
    });
  });
}