我有以下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
收到以下错误。所以我handleService
中的notificationService
在这里没有定义,但为什么呢?它注入到构造函数中,并且在 succes
-方法上正常工作。为什么它在error
方法中不起作用?
我的猜测: 当作为参数传递且未执行(在deleteCustomer
函数内部(时,this.handleService.error
的作用域是不同的。
将其替换为this.handleService.error.bind(this)
你的 app.module.ts 中有你的服务吗?
providers: [HandleService,NotificationService],
在 App.module.ts 中的提供程序数组上添加服务,或者可以使用:
@Injectable({
providedIn: 'root'
})
不需要向 app.module.ts 添加任何提供程序
只需在您的服务类之前添加装饰器
@Injectable({
providedIn: 'root'
})
export class CustomerService
与句柄服务相同