簡體   English   中英

Angular:Observable with subscribe 返回錯誤 200 OK 因為響應不是 JSON

[英]Angular: Observable with subscribe returns error 200 OK as the response is not JSON

我正在使用 Angular 11 開發一個前端 Web 應用程序。該應用程序使用多個以 JSON 格式返回數據的服務。 我使用async / await javascript 構造和Observables從這些服務中獲取答案。 這是我打電話的一個例子:

let myResponse = await this.myService(this.myData);
myResponse.subscribe(
   res => {
    console.log("Res: ",res)
   }, (error) => {
    console.log("Error: ",error)
   }
);

其中this.myService包含使用 Angular httpClient進行 HTTP 調用的代碼。 不幸的是,特定服務(只有一個!)不以 JSON 格式返回數據,但它返回一個字節數組(標識 pdf 格式application/pdf字符串)。 不幸的是,這個調用會導致一個非常奇怪的錯誤,代碼為 200 OK:

在此處輸入圖片說明 在此處輸入圖片說明

如何防止res被解釋為 JSON 並因此報告此錯誤? 我如何閱讀res報告它不會是 json 格式

此服務沒有錯誤(使用 Postman 可以完美運行)。 問題是 Javascript 和 Observable 被解釋為 JSON。 在這種情況下如何讀取res的內容?

如果 HTTP API 調用未返回JSON ,只需在responseType選項中提供正確的值:

this.httpClient.get('<URL>', {
      responseType: 'arraybuffer'
});

參考: https : //angular.io/api/common/http/HttpClient#description

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM