angular json 错误中的 Httpclient 请求
Httpclient request in angular json error
我正在做 http 客户端请求
export class MapjsonService{
theUrl = 'http://localhost:4200/api/Lat_Long.json';
constructor(private http: HttpClient) { }
fetchNews(): Observable<any>{
return this.http.get(this.theUrl)
}
它在大约 99.99% 的时间内都在工作,遗憾的是,这是 运行 如此频繁,就像每 10 分钟一次失败
HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "http://localhost:4200/api/Lat_Long.json", ok: false, …}
和
"Http failure during parsing for http://localhost:4200/api/Lat_Long.json"
现在我出于某种原因弄清楚了我来自 newrelic 的 nrql 查询(这是存储在'/api/lat_long.json'中的内容,每个橙色都没有最后一次关闭'}'月亮。这就是引发此错误的原因。我的问题是我有什么办法可以检查返回值是否有效 json,如果无效,请在不终止进程的情况下再次尝试 GET
请求那个叫它的。谢谢
您的代码抛出错误,因为 json 不正确,因此无法解析,因此可观察对象抛出错误:
fetchNews(): Observable<any>{
return this.http.get(this.theUrl)
}
默认情况下,http 客户端期望 json 因为这通常是用户对它的期望。也不总是这样,比如你现在的情况。
我们可以通过使用 {responseType: 'text'}
参数指定我们想要的内容来告诉 http 客户端不要自行解析 json。
fetchNews(): Observable<any>{
return this.http.get(this.theUrl, {responseType: 'text'})
}
但是您需要尽可能解析 json。因此,如果可能的话,我们将在此处映射可观察对象并解析内容。
fetchNews(): Observable<any>{
return this.http.get(this.theUrl, {responseType: 'text'}).map(res => {
try{
return JSON.parse(res);
} catch {
return null;
}
})
}
然后随便你怎么弄,observable返回的值如果解析不出来就是null
RXJS 6 语法:
fetchNews(): Observable<any>{
return this.http.get(this.theUrl, {responseType: 'text'}).pipe(
map(res => {
try{
return JSON.parse(res);
} catch {
return null;
}
})
)
}
我正在做 http 客户端请求
export class MapjsonService{
theUrl = 'http://localhost:4200/api/Lat_Long.json';
constructor(private http: HttpClient) { }
fetchNews(): Observable<any>{
return this.http.get(this.theUrl)
}
它在大约 99.99% 的时间内都在工作,遗憾的是,这是 运行 如此频繁,就像每 10 分钟一次失败
HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "http://localhost:4200/api/Lat_Long.json", ok: false, …}
和
"Http failure during parsing for http://localhost:4200/api/Lat_Long.json"
现在我出于某种原因弄清楚了我来自 newrelic 的 nrql 查询(这是存储在'/api/lat_long.json'中的内容,每个橙色都没有最后一次关闭'}'月亮。这就是引发此错误的原因。我的问题是我有什么办法可以检查返回值是否有效 json,如果无效,请在不终止进程的情况下再次尝试 GET
请求那个叫它的。谢谢
您的代码抛出错误,因为 json 不正确,因此无法解析,因此可观察对象抛出错误:
fetchNews(): Observable<any>{
return this.http.get(this.theUrl)
}
默认情况下,http 客户端期望 json 因为这通常是用户对它的期望。也不总是这样,比如你现在的情况。
我们可以通过使用 {responseType: 'text'}
参数指定我们想要的内容来告诉 http 客户端不要自行解析 json。
fetchNews(): Observable<any>{
return this.http.get(this.theUrl, {responseType: 'text'})
}
但是您需要尽可能解析 json。因此,如果可能的话,我们将在此处映射可观察对象并解析内容。
fetchNews(): Observable<any>{
return this.http.get(this.theUrl, {responseType: 'text'}).map(res => {
try{
return JSON.parse(res);
} catch {
return null;
}
})
}
然后随便你怎么弄,observable返回的值如果解析不出来就是null
RXJS 6 语法:
fetchNews(): Observable<any>{
return this.http.get(this.theUrl, {responseType: 'text'}).pipe(
map(res => {
try{
return JSON.parse(res);
} catch {
return null;
}
})
)
}