0

我訂購了一個服務,我從外部API請求圖像URL並將其存儲在共享服務中。我的訂閱沒有處理錯誤

邏輯:
1.清空當前圖像陣列從API
2.請求圖像,並且將其推到(新清除的)陣列(響應=>)
3.如果URL返回一個錯誤,使用默認(佔位符)圖像填充陣列(錯誤=>)

由於某些原因,儘管存在錯誤,但仍未處理該錯誤。 我已發佈我的組件和錯誤消息的上下文。

Component.ts

getImages(vehicleID: number, color: string): void { 
    this._carConfigService.car.colors.exterior.urls = []; 
    this._FAPIService.getImagesForColors(vehicleID, color) 
     .subscribe(
     response => { 
     response.products[0].productFormats.forEach(pF => { 
     this._carConfigService.car.colors.exterior.urls.push(pF.assets[0].url); 
     }); 
     }, 
     error => { 
      this.errorMessage = <any>error; 
      if (this._carConfigService.car.colors.exterior.urls.length === 0) { 
      this._carConfigService.car.colors.exterior.urls = this._carConfigService.defaultImages; 
      } 
     }); 
    } 

我收到以下錯誤:

Failed to load resource: the server responded with a status of 422() 
EXCEPTION: Response with status: 0 for URL: null 
Uncaught Response 
+1

你可以用'onCatch'方法處理錯誤,你寫的服務,然後地圖後扔那麼你的用戶將能夠處理它 –

+0

@BabarBilal,這可能是我在尋找解決方案因爲,你可以發佈一個示例代碼片段,以便我可以將你的答案標記爲正確嗎?謝謝:) – Moshe

+0

Im從手機不能發佈代碼段添加2個鏈接都有解決您的問題祝您好運。 –

回答

1

您需要使用具有異常處理

export class TaskService { 
    private _url = "api/products/datanew.json"; 
    constructor(private _http: Http) { 
    } 
    getTasks(): Observable<any[]> { 
     return this._http.get(this._url) 
      .map((response: Response) => <any[]>response.json()) 
      .do(data => console.log("data we got is " + JSON.stringify(data))) 
      .catch(this.handleError); 

    } 
    private handleError(error: Response) { 
      console.log(error); 
      return Observable.throw(error.json().error || 'Internal Server error'); 
    } 
} 

另外的常規方法來處理他們,我有一個問題。

  1. 你正在獲取數據,但你沒有分配給任何對象?沒有返回類型
+0

我的檢索響應帶有很多不必要的屬性,所以我遍歷對象只得到我需要的並將其推送到一個數組。我的服務,但是我想用默認圖像更新我的圖像,如果我的訂閱返回錯誤響應。 – Moshe

+0

這可以很容易地處理服務本身。爲什麼你複雜的東西? – Aravind

+0

你可以詳細說明服務如何處理? – Moshe