注入的服务未定义

时间:2019-11-20 14:29:41

标签: angular

我有以下HandleService

@Injectable()
export class HandleService {

  constructor(private notificationService: NotificationService) {
  }

  success(message: string) {
    this.notificationService.printSuccessMessage(message);
  }

  error(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
      // A client-side or network error occurred. Handle it accordingly.
      this.notificationService.printErrorMessage(error.error.message);
      console.error('An error occurred:', error.error.message);
    } else {
      // The backend returned an unsuccessful response code.
      // The response body may contain clues as to what went wrong,
      this.notificationService.printErrorMessage(error.message);
      console.error(
        `Backend returned code ${error.status}, ` +
        `body was: ${error.error}`);
    }
    // return an observable with a user-facing error message
    return throwError(
      'Something bad happened; please try again later.');
  };
}

然后就是使用的NotificationService

@Injectable()
export class NotificationService {
  private _notification: any = alertify;

  constructor() {
  }

  openConfirmationDialog(message: string, okCallback: () => any) {
    this._notification.confirm(message, function (e) {
      if (e) {
        okCallback();
      } else {
      }
    });
  }

  printSuccessMessage(message: string) {

    this._notification.success(message);
  }

  printErrorMessage(message: string) {
    this._notification.error(message);
  }

  openAlertDialog(message: string) {
    this._notification.alert(message);
  }
}

我这样使用HandleService

@Injectable()
export class CustomerService {

constructor(public http: HttpClient, private authService: AuthService,
              private handleService: HandleService) {
  }

deleteCustomer(customer: Customer): Observable<any> {
    return this.http.delete(BASE_URL + customer.id, this.authService.setHeaders('application/json'))
      .pipe(
        tap(() => this.handleService.success(`Deleted customer: ${customer.name}`)),
        catchError(this.handleService.error)
      );
  }
}

因此,当一切正常时,将执行this.handleService.success('Deleted customer: ${customer.name}'),它会按预期工作。如果发生错误,将执行this.handleService.error,但不会显示错误消息,而是出现以下错误cannot read property 'printErrorMessage' of undefined。因此我的notificationService中的handleService在这里未定义,但是为什么呢?它注入了构造函数,并且可以在succes方法上正常工作。为什么它不能在error方法中起作用?

4 个答案:

答案 0 :(得分:1)

您在app.module.ts中有服务吗?

providers: [HandleService,NotificationService],

答案 1 :(得分:1)

我的猜测: this.handleService.error的范围作为参数传递而未执行时(在deleteCustomer函数内部)。

this.handleService.error.bind(this)

替换

答案 2 :(得分:0)

在App.module.ts中的提供程序数组上添加服务,或者您可以使用:

 @Injectable({
  providedIn: 'root'
})

答案 3 :(得分:0)

您无需将任何提供程序添加到app.module.ts

只需在服务类之前添加装饰器

@Injectable({
  providedIn: 'root'
})
export class CustomerService

与HandleService相同