2017-04-12 56 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 => { 
    })