Reputation: 393
In my Angular 2 app, I tried to catch an error on a component level that is thrown from service.
For instance.
class ServiceA
{
getCustomer()
{
this.http.get('/someURL').subscribe(
(data) => {
return data;
},
(err) => {
throw err
}
)
}
class ComponentA
{
constructor(
private serviceA : ServiceA
){}
ngOnInit()
{
try
{
let var1;
var1 = this.serviceA.getCustomer()
}
catch(err)
{
//How do I trigger this catch to work ?
console.log(err);
}
}
}
What is wrong in my code above ? Why isn't it working ?
Upvotes: 1
Views: 8429
Reputation: 29635
You are subscribing in the service itself and not in the component. Also getCustomer()
is not returning anything.
Return just the observable from getCustomer()
. Map the Response value.
getCustomer()
{
return this.http.get('/someURL').map(
(data) => {
return data.json();//if response content type is json
},
(err) => {
throw err
}
)
}
Subscribe in component.
this.serviceA.getCustomer().subscribe(data=>{
var1=data;
},err=>{
console.log(err);//get the error in error handler
});
Upvotes: 2