Angular2-捕获错误并在视图中显示 [英] Angular2- Catch error and display it in view
本文介绍了Angular2-捕获错误并在视图中显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个执行获取请求并引发错误的服务。
I have a service that performs get request and throws the error.
service.ts
return this.http.get(/apiUrl)
.map(
(response: Response) => {
const items = response.json();
return items;
})
.catch(
(error: Response) => {
return Observable.throw(error);
});
}
我订阅了该组件,并希望在视图中显示错误。我搜索了此异常处理,但无法获得相关的答案该怎么办?
I subscribe it to the component and I want to display the error in view. I searched for this exception handling but I couldnot get relevant answers how do I do it?
component.ts
this.faqService.getServers()
.subscribe(
(data) => {
this.item = data.items;
console.log(this.item);
},
(error) => console.log(error)
);
});
我可以在控制台中看到如何在视图中显示错误。
I can see the error in console how to display it in the view.
错误
推荐答案
分配一个变量,然后显示
Assign to a variable and then display
在ts中声明一个变量
errorMessage : string;
然后,
this.faqService.getServers()
.subscribe(
(data) => {
this.item = data.items;
console.log(this.item);
},
(error) => {
this.errorMessage= error.error_message;
}
);
});
然后使用HTML
<h1>{{errorMessage}}</h1>
您需要从服务中返回错误,
You need to return the error from your service,
return this.http.get(/url)
.map(
(response: Response) => {
return response.json();
})
.catch(
(error: Response) => {
return Observable.throw(error.json());
});
}
这篇关于Angular2-捕获错误并在视图中显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文