2017-04-12 58 views
0

我寫了下面的代碼在角2項目:Angular 2 Http:爲什麼不嘗試catch機制的工作?

ngOnInit() { 
    try { 
     this.http.request("http://29.media.tumblr.com/ZabOTt2mpdp8ljaxp88lwdhP_400.jpg").subscribe((res: Response) => { 
     console.log(res.url); 
     this.urls.push(res.url); 
     }); 
    } catch(e) { 
     console.log("Error"); 
    } 
    } 

好了,路「http://29.media ......」被打破了。我期望try塊內的代碼會產生錯誤,然後catch塊內的代碼將被激活。但不是。我得到的是一個錯誤。你知道爲什麼嗎?

順便說一下,這裏沒有同源策略問題。

回答

1

因爲它像承諾​​一樣是異步的。該函數在拋出任何異常之前已經返回。

您可以使用

...subscribe(
    res => { 
    }, 
    err => { 
    }) 
相關問題