[英]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.