ionic3如何在ErrorHandlerService中注入服务/提供者

时间:2018-04-01 11:10:40

标签: javascript angular ionic-framework

  

问题

=======

当我在ErrorHandlerService中注入ConfigService来呈现toast时,给我一个错误:errorHandlerService.ts:36  它发生了:错误:未捕获(在承诺中):TypeError:无法读取未定义的属性'_appLog'

 export class ErrorHandlerService implements ErrorHandler {

      private _appLog: ConfigService;
      constructor (private injector: Injector) {
        setTimeout(() => {
          this._appLog = injector.get(ConfigService);
        }, 0);
      }
      handleError(error: Error | HttpErrorResponse) {

          if (error instanceof HttpErrorResponse) {
              if (!navigator.onLine) {
                console.log('Please, check your internet connection');

              } else if(error.status === 401){
                console.log(error.message);
                this._appLog.presentToast();

              }else {
                console.log(error.message);
              }
            } else {
              console.log('Not Http Error');
          }
          // Log the error anyway
          console.error('It happens: ', error);
      }  
    }


    @Injectable()
    export class ConfigService {

        constructor(private storage: Storage){
        }

        presentToast(){
            console.log("test");
        }
    }


 getUsers(){
        let promise = new Promise((resolve, reject) => {
            let apiURL = `${this.configS.apiRootV1}/users`;
            this.http.get(apiURL).toPromise()
                .then((res) => {

                    console.log(res);
                    resolve(res);

                }).catch(this.errorHandlerService.handleError);
        });
        return promise;
    }

1 个答案:

答案 0 :(得分:2)

handleError函数中的

'this'未定义。尝试使用'bind'发送'this'的值:

.catch(this.errorHandlerService.handleError.bind(this.errorHandlerService));