我设置了一个简单的通知服务:
@Injectable({
providedIn: 'root',
})
export class NotificationService {
constructor(private snackBar: MatSnackBar) {}
public openSnackbar(message: string, panelClass: string = 'success') {
this.snackBar.openFromComponent(SnackbarComponent, {
data: message,
panelClass: panelClass,
});
}
public handleError(response: any): void {
if (!response.error?.message) return;
this.snackBar.openFromComponent(SnackbarComponent, {
data: response.error?.message,
panelClass: 'warning',
});
}
}
这用于设置我的snackbar消息和处理httpresponse错误。如果我这样使用它:
.subscribe(
() => {
this.loading = false;
this.notificationService.openSnackbar(
'An email was sent to your email address. Please click the link and follow the instructions.'
);
this.router.navigate(['/login']);
},
(response: any) => this.notificationService.handleError(response)
);
所有这些都很好用。我想更改这条线路:
(response: any) => this.notificationService.handleError(response)
到此:
this.notificationService.handleError
但当我这样做时,我在通知服务中收到一个错误,上面写着:
无法读取未定义的属性"openFromComponent">
我认为这是因为">这个";不再是服务。如果我将其更改为后一种模式,我如何从方法访问this?
您应该绑定上下文
this.notificationService.handleError.bind(this.notificationService)