我从一个服务器接收了大约multipart/mixed个内容,其中包含一些JSON和字节,需要将其解析为Angular中的一个对象.

这就是我发送请求的方式:

public sendRequest(headerData: string): Observable<MultipartResponse> {

    let requestHeaders: HttpHeaders = new HttpHeaders();
    requestHeaders = requestHeaders.set("X-Header-Data", headerData);
    
    return httpClient.get("localhost:12345/myroute", { headers: requestHeaders}) as Observable<MultipartResponse>;
}

我实现了一个HttpInterceptor来解析响应,如下所示:

@Injectable({ providedIn: 'root' })
export class MyInterceptor implements HttpInterceptor {

    public intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        return next.handle(request).pipe(map((event: HttpEvent<any>) => {

            if (event instanceof HttpResponse)
                return response.clone({ body: new MultipartResponse(event.body); });

            return event;
        }));
    }
}

然后把它注册成main.ts

bootstrapApplication(AppComponent, {
  providers: [
    importProvidersFrom(HttpClientModule),
    provideHttpClient(withInterceptorsFromDi()),
    {
      provide: HTTP_INTERCEPTORS,
      useClass: MyInterceptor,
      multi: true
    }
  ],
}).catch((err) => console.error(err));

现在,当我发出请求时,拦截器在确认请求已成功发送的Sent事件上触发一次,但之后再也没有触发过.相反,响应直接进入调用方,然后调用方抛出错误,因为它试图将整个正文解析为JSON.

推荐答案

因为它出错:因为没有设置响应类型,所以它使用默认的JSON解析器(必须预先设置响应类型),然后在try 解析响应时出错,永远不会到达您的拦截器方法(拦截器可以用catchError((error: HttpErrorResponse) => {...捕获它).

因此,您需要禁用默认解析器.您可以添加一些标志来判断请求是否包含您的多部分头数据,然后通过将响应类型更改为text来禁用JSON解析器,然后使用您的自定义解析器解析响应(根据需要定制):

public intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    const isMixedReq = request.headers.get('X-Header-Data');

    if (isMixedReq && request.responseType === 'json') {

      request = request.clone({responseType: 'text'});

      return next.handle(request).pipe(map((response: HttpEvent<any>) => {

        if (response instanceof HttpResponse && typeof response.body === 'string')
            return response.clone({ body: new MultipartResponse(response.body) });

        return response;
      }));
  } else {
    return next.handle(request);
  }
}

接近来源:Custom JSON parsing

Angular相关问答推荐

*ngFor循环中令人困惑的Angular 行为

如何跨不同组件使用ng模板

在状态更新后是否会再次触发ngrx效果?

如何确保[共享]组件是真正的哑组件?(Angular )

Angular react 形式验证问题

Primeng:安装ANGLE 16.2.0版本

获取 Angular 中所有子集合 firestore 的列表

Angular Http 拦截器 - 修改标头会导致 CORS

Angular 升级后 RXJS SwitchMap 无法与解析器一起正常工作

需要做什么才能使 ErrorHandler 正常工作?

模块内的命名路由出口 - 路径匹配但内容未加载

Error: Module not found: Error: Can't resolve '@angular/cdk/scrolling'

错误:formControlName 必须与父 formGroup 指令一起使用.您需要添加一个 formGroup 指令

如何在 ANGULAR 2 中提交表单时重置表单验证

Angular2 Base64 清理不安全的 URL 值

@angular/platform-b​​rowser 与 @angular/platform-b​​rowser-dynamic

Angular 2:将外部js文件导入组件

如何使用无头浏览器运行测试?

如何对 *ngFor 应用数量限制?

Angular CLI 为已经存在的组件创建 .spec 文件