简体   繁体   English

从服务可观察到的组件捕获错误

[英]Catch error from component thrown by service observable

In my Angular 2 app, I tried to catch an error on a component level that is thrown from service. 在我的Angular 2应用程序中,我尝试捕获从服务抛出的组件级别的错误。

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 ? 为什么不起作用?

You are subscribing in the service itself and not in the component. 您正在订阅服务本身,而不是组件。 Also getCustomer() is not returning anything. 而且getCustomer()不返回任何东西。

Return just the observable from getCustomer() . 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
  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM