2

I have a simple notification service set up:

@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',
    });
  }
}

This is used to set my snackbar messages and handle httpresponse errors. If I use it like this:

.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)
);

All of it works fine. I would like to change this line:

(response: any) => this.notificationService.handleError(response)

to this:

this.notificationService.handleError

But when I do, I get an error in my notification service stating:

Cannot read property 'openFromComponent' of undefined

I think it's because "this" is no longer the service. How can I access this from the method if I change it to the latter pattern?

r3plica
  • 13,017
  • 23
  • 128
  • 290

1 Answers1

1

You should bind the context

this.notificationService.handleError.bind(this.notificationService)