简体   繁体   English

从Angular组件的服务中捕获Promise错误

[英]Catch error in promise from a service in an Angular component

Hi everyone running into a problem with a post service I created in angular. 大家好,我在角度创建的邮政服务遇到了问题。 Struggling to catch the error from my component when I call the service. 当我调用服务时,努力从组件中捕获错误。 I was able to catch the error from the service but I need to do this from my component to properly handle the error. 我能够从服务中捕获错误,但是我需要从组件中执行此操作以正确处理错误。 Any advice would be greatly appreciated. 任何建议将不胜感激。

Service 服务

sendData(obj) {
 let promise = new Promise((resolve) => {
   this.http.post(this.URL, obj, this.httpOptions)
     .toPromise()
     .then(
      res => {
        console.log(res);
        resolve(res);
      }
     )
     //.catch((err) => { 
     //  console.log(err);
     //  throw err;
     //});
   });
  return promise;
}

Component 零件

this._myservice.sendData(this.myobj)
  .then(function (res) {
    console.log('data sent');
  })
  .catch(error => {
      console.warn('from component:', error);
      // this console warn never gets logged out
  });

Do I need to update something in my service to allow me to catch the error from the component? 我是否需要更新服务中的某些内容以允许我从组件中捕获错误?

You're creating your own Promise here, but you never call reject if the Promise you're wrapping rejects (throws an error). 您在此处创建自己的Promise ,但是如果您要包装Promise 拒绝 (引发错误),则永远不要调用reject This is known as the the new Promise antipattern . 这被称为new Promise反模式 In your case, you can simply remove this wrapper and replace the call to resolve with a return in order to achieve what you need, like so: 在您的情况下,您可以简单地删除此包装器,并用return代替要resolve的调用,以实现所需的功能,例如:

sendData(obj) {
    return this.http.post(this.URL, obj, this.httpOptions)
        .toPromise()
        .then(res => {
            console.log(res);
            return res;
        });
}

In order to provide more context, you could fix your original problem by calling reject . 为了提供更多上下文,您可以通过调用reject解决原始问题。 This would look like this: 看起来像这样:

// DONT'T DO THIS
sendData(obj) {
   let promise = new Promise((resolve, reject) => {
       this.http.post(this.URL, obj, this.httpOptions)
           .toPromise()
           .then(res => {
               console.log(res);
               resolve(res);
            })
            .catch((err) => { 
                console.log(err);
                reject(err); // Here.
            });
        });
    return promise;
}

But, as I said above, this is overcomplicated and unnecessary. 但是,正如我上面说的那样,这过于复杂且不必要。 I hope that it demonstrates how the Promise your component has access to could never see errors that occurred in the HTTP call. 我希望它能演示您的组件对Promise的访问方式如何永远不会看到HTTP调用中发生的错误。

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

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