【问题标题】:How to intercept response that is non JSON如何拦截非 JSON 的响应
【发布时间】:2018-05-10 17:44:59
【问题描述】:

我正在使用 Angular 5.1.0 并尝试读取从服务器发送的文件作为对 GET 请求的响应。

我正在这样做:

  getImage(imageUrl: string) {
    const httpOptions = {
      headers: new HttpHeaders({
        'Authorization': 'Basic ' + this.authService.getBasicAuthString(),
        resourceType: 'blob'
      })
    };
    return this.http.get<File>(imageUrl, httpOptions);
  }

但是,看起来,标记为已修复 here 的错误在 5.1.0 中并未修复,并且不断收到 HttpErrorResponse 说它无法解析收到的响应(响应代码为 200)。

我正在尝试为 5.1.0 重写错误中提供的解决方法,但那里的社区反应不快。

解决方法是:

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req).catch(event => {
      if (event instanceof HttpErrorResponse) {
        const response = event as HttpErrorResponse;
        if (response.headers.get('content-type') === 'application/json') {
          return Observable.throw(new HttpErrorResponse({
            error: JSON.parse(response.error),
            headers: response.headers,
            status: response.status,
            statusText: response.statusText,
            url: response.url,
          }));
        }
      }
      return Observable.throw(event);
    })
}

看起来不错,但是问题如下: Property 'catch' does not exist on type Observable&lt;HttpEvent&lt;any&gt;&gt;.

谁能帮我解决这个问题,因为我不是 Angular 大师。

Ritwick Dey 回答后更新(我不回答第一部分,因为在其他人看来,这不是很好的问题):

现在,一切都找到了,我不需要抛出并传递所有其他拦截器,并将原始响应返回给我的 GET 方法的订阅者。我不想要一个 throw,因为它再次以相同消息的错误出现:

message: "Http failure during parsing for **logo-url**"
​
name: "HttpErrorResponse"

我想使用 of(),如 here 所述,但是在将 return Observable.throw(event); 替换为 return of(req); 时出现以下错误:

ERROR in src/app/shared/parser.interceptor.ts(16,5): error TS2322: Type 'Observable<{} | HttpProgressEvent | HttpSentEvent | HttpHeaderResponse | HttpResponse<any> | Http...' is not assignable to type 'Observable<HttpEvent<any>>'.
  Type '{} | HttpProgressEvent | HttpSentEvent | HttpHeaderResponse | HttpResponse<any> | HttpUserEvent<a...' is not assignable to type 'HttpEvent<any>'.
    Type '{}' is not assignable to type 'HttpEvent<any>'.
      Type '{}' is not assignable to type 'HttpUserEvent<any>'.
        Property 'type' is missing in type '{}'.
src/app/shared/parser.interceptor.ts(31,14): error TS2304: Cannot find name 'of'.

OF 使用以下子句导入:

import 'rxjs/add/observable/of';

【问题讨论】:

标签: javascript angular typescript


【解决方案1】:

你有没有从 rxjs 导入 catch 操作符?

import 'rxjs/add/operator/catch'

如果您使用的是 Rxjs 5.5,请关注此https://stackoverflow.com/a/47203943/6120338

【讨论】:

  • 很好,我会用以下问题更新我的答案:)
猜你喜欢
  • 2022-07-12
  • 1970-01-01
  • 2012-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-02
  • 1970-01-01
  • 2016-05-02
相关资源
最近更新 更多