Can AngularJS set the responseType after a response has been received?

后端 未结 1 1543
陌清茗
陌清茗 2021-01-05 05:13

I have an Angular 1.x application that is expecting to receive a binary file download (pdf) using a $http.post() call. The problem is, I\'d like to alternative

相关标签:
1条回答
  • 2021-01-05 05:45

    An XHR responseType property can not be changed after a response has been loaded. But an arraybuffer can be decoded and parsed depending on Content-Type:

     var config = {
        responseType: "arraybuffer",
        transformResponse: jsonBufferToObject,
      };
    
      function jsonBufferToObject (data, headersGetter, status) {
          var type = headersGetter("Content-Type");
          if (!type.startsWith("application/json")) {
            return data;
          };
          var decoder = new TextDecoder("utf-8");
          var domString = decoder.decode(data);
          var json = JSON.parse(domString);
          return json;
      };
    
      $http.get(url, config);
    

    The above example sets the XHR to return an arraybuffer and uses a transformResponse function to detect Content-Type: application/json and convert it if necessary.

    The DEMO on PLNKR

    0 讨论(0)
提交回复
热议问题