简体   繁体   中英

ionic3 how can i inject service/provider inside ErrorHandlerService


Question

=======

When i am injecting ConfigService inside ErrorHandlerService to present toasts, gives me an error: errorHandlerService.ts:36 It happens: Error: Uncaught (in promise): TypeError: Cannot read property '_appLog' of undefined

 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;
    }

in handleError function 'this' is undefined. Try to send the value for 'this' using 'bind':

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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