簡體   English   中英

Angular4-如何檢測響應是JSON還是可觀察的純文本

[英]Angular4 - How to detect if a response is JSON or plain text with observable

我想知道當使用通用api服務調用各種終結點時,是否有一種方法可以以可觀察的方式檢測響應的格式。 有些發送回JSON,其他發送純文本。

this.http.get(endpoint).map(response => {
    // if JSON
    return response.json();
    // else if plain text
    return response.text();
})...

角度文檔中存在ResponseContentType ,但是我在響應對象中從未找到此枚舉,所以我使用了“技巧”:

this.http.get(endpoint).map(response => {
    const contentType = res.headers.get('Content-type');
   if (contentType == 'application/json') {
    return response.json();   
   } else if (contentType == 'application/text') {
    return response.text();
   }
})...

如果有人知道我們在哪里可以找到ResponseContentType枚舉,請告訴我們!

我從來沒有找到過使用Angular來驗證JSON的內置方法,所以我只檢查了響應標頭中的內容類型。

這是我使用的功能:

/**
 * True of the response content type is JSON.
 */
private static isJson(value: Response): boolean {
    return /\bapplication\/json\b/.test(value.headers.get('Content-Type'));
}

Content-Type的字符串中可以包含其他內容,因此為了確保安全,我使用了正則表達式。

如果不是JSON,我建議失敗。

 this.http.get().map((value:Response)=>{
      if(this.isJson(value)) {
         return value;
      }
      throw value;
 });

然后,您可以稍后在訂閱服務器中捕獲已知的JSON響應。 現在,您知道訂閱​​服務器中的所有響應都在獲取JSON。

暫無
暫無

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

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