2016-08-12 47 views
0

我有一個服務,它向http發送一個http get請求。 這裏是我的代碼:angualr2:http.get 404例外處理

@Injectable() 
export class InstagramService { 
    constructor(private _http:Http){    

    } 
    getGallery(username: string) : Observable<dataSet> { 

     return this._http.get("http://www.instagram.com/"+username+"/media/").map(res => res.json(), 
                       (err)=>console.log("Error is:"+err)); 

    } 
} 

,有時我得到一個404例外,我需要處理這個例外,並且不讓它出現在我的控制檯。我認爲(err)=>console.log("Error is:"+err) 可能會有幫助,但錯誤仍在控制檯中。

我看過this,但有沒有一種更簡單的方法來處理這種異常,而不需要服裝異常處理程序?

回答

0

您還可以充分利用catch操作:

@Injectable() 
export class InstagramService { 
    constructor(private _http:Http){    

    } 
    getGallery(username: string) : Observable<dataSet> { 

    return this._http.get("http://www.instagram.com/"+username+"/media/") 
     .map(res => res.json()) 
     .catch(err => { // <----- 
     // do something when error occurs 
     }); 
    } 
} 
+1

有一個錯誤: ** [TS] 住宅 '抓' 不上鍵入 '可觀測' 存在** –

+0

是的,你需要明確包含它:'import'rxjs/add/operator/catch';'。看到這個問題:http://stackoverflow.com/questions/34515173/angular-2-http-get-with-typescript-error-http-get-map-is-not-a-function-in/34515276#34515276 –

+0

對不起,在** catch **我需要返回一些調用方法,它顯示404發生。我預計** null **可以幫助我,但似乎我應該返回一個** Observable **。和**數據集**是一個接口,所以我可以用返回值完成你的答案? –