【问题标题】:Angular 8 HttpClient GET ignoring responseType: 'blob' from swagger API returning {}Angular 8 HttpClient GET忽略responseType:来自swagger API的'blob'返回{}
【发布时间】:2020-08-11 08:20:06
【问题描述】:

像这样在 swagger 2.0 中指定一个 API 服务:

 /example/my-file:
    get:
      summary: Get this file
      tags:
        - MyFile
      produces:
        - application/octet-stream
      responses:
        200:
          description: OK
          schema:
            type: file
        400:
          $ref: "#/responses/badRequest"
        404:
          $ref: "#/responses/notFound"
        500:
          $ref: "#/responses/internalServerError"

已实现并可发出正确返回文件内容的 Postman GET 请求。 我使用 ng-swagger-gen 生成了一个角度服务调用:

getExampleFileResponse(params: ExampleService.GetExampleFileParams): __Observable<__StrictHttpResponse<Blob>> {
    let __params = this.newParams();
    let __headers = new HttpHeaders();
    let __body: any = null;


    let req = new HttpRequest<any>(
      'GET',
      this.rootUrl + `/example/my-file`,
      __body,
      {
        headers: __headers,
        params: __params,
        responseType: 'blob'
      });

    return this.http.request<any>(req).pipe(
      __filter(_r => _r instanceof HttpResponse),
      __map((_r) => {
        return _r as __StrictHttpResponse<Blob>;
      })
    );
  }


  getExampleFile(params: ExampleService.GetExampleFileParams): __Observable<Blob> {
    return this.getExampleFileResponse(params).pipe(
      tap(_r => console.log(_r)),
      __map(_r => _r.body as Blob)
    );
  }

当我从 Angular 客户端调用时:

   this.ExampleService.getExampleFile(param)
    .subscribe((f) => {
      saveAs(f, 'example.txt')
    });

我得到一个由 3 个字节组成的 Blob:{}\n 不是文件内容。服务中的某些内容似乎无法正常工作。如果我在响应中将 tap() 放入服务中,我可以看到响应正在传递具有这三个字节和内容类型的 Blob:application/json,而不是我在 API 中指定的 application/octet-stream。

【问题讨论】:

    标签: angular blob content-type


    【解决方案1】:

    好的。缺少一条信息:我们正在使用拦截器来注入身份验证令牌。我们需要添加并接受:application/json、application/octet-stream、/' 项,以便文件 blob 可以脱离 GET。角度文档声明 HttpClient.get() 的默认返回是 JSON。我们只需要指定接受的返回类型。

    【讨论】:

      猜你喜欢
      • 2020-07-06
      • 2018-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-04
      相关资源
      最近更新 更多