如何捕获Angular2中的错误,Angular 2错误:未处理的Promise拒绝

时间:2018-03-08 18:40:48

标签: angular

我有一个使用service.js的header.component.ts。 service.js将检测balanceObservable对象上的任何更改,然后更改header.compnoent.ts行为。如代码中所示,如果出现错误,服务将拒绝(错误),但component.ts无法收到错误,而是提供zone.js:484 Unhandled Promise rejection

enter image description here

service.js

  public balanceObservable = new Subject<string[]>();

  refreshBalance (address) {
      var self = this;
      return new Promise (function (resolve, reject) {
        self.getBalance(self.wallet.address, function (error, result) {
          if (error) {
            reject(error);
          } else {
            self.balanceObservable.next(result);
            resolve(result);
            }
        })
      })
    }

header.component

  watchBalance(){
    var self = this;
     const subscription = this.service.balanceObservable.subscribe((result) => {
      console.log('watchBalance',result);
    },
    (err) => {
      console.log('watchBalance err',err);
      }
    )
 }

后来我试图抓住catch中的错误。

this.service.balanceObservable.subscribe((result) => {},)
.catch(e => console.log("reject: " + e));

但也有错误Property 'catch' does not exist on type 'Subscription'.

1 个答案:

答案 0 :(得分:0)

service.js

  public balanceObservable = new Subject<string[]>();

  refreshBalance (address) {
      var self = this;
      return new Promise (function (resolve, reject) {
        self.getBalance(self.wallet.address, function (error, result) {
          if (error) {
            reject(error);
          } else {
            self.balanceObservable.next(result);
            resolve(result);
            }
        })
      })
      .catch((e) => {
        console.log('Here we catch the promise error');
      })
    }

header.component

  watchBalance(){
    var self = this;
     const subscription = this.service.balanceObservable.subscribe((result) => {
      console.log('watchBalance',result);
    }
 }