簡體   English   中英

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;
      }
    })
  )
}

暫無
暫無

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

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