Angular2- 捕获错误并将其显示在视图中 [英] Angular2- Catch error and display it in view
本文介绍了Angular2- 捕获错误并将其显示在视图中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个执行 get 请求并抛出错误的服务.
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 中声明一个变量
declare a variable in your 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屋!
查看全文