我正在使用 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 重写错误中提供的解决方法,但那里的社区 react 不是很好。
解决方法是:
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<HttpEvent<any>>
.
谁能帮我解决这个问题,因为我不是 Angular 大师。
在 Ritwick Dey 回答后更新(我没有回答第一部分,因为在其他人看来,这不是很好的问题):
现在,当一切都已找到时,我不需要抛出并传递所有其他拦截器并将原始响应返回给我的 GET 方法的订阅者。我不想抛出,因为它再次作为错误出现并带有相同的消息:
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';
最佳答案
你有没有从 rxjs 导入 catch
运算符?
import 'rxjs/add/operator/catch'
如果您使用的是 Rxjs 5.5,请遵循此 https://stackoverflow.com/a/47203943/6120338
关于javascript - 如何拦截非 JSON 的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50278621/