Konstantin
Konstantin

Reputation: 139

How to fix Cannot read property 'next' of undefined?

In API service I want to add the error to notification. processError method is called in http request with binding : catchError(error=>this.processError(error)),

api.service:

private processError(res: HttpErrorResponse) {
    this.currentErrorSubject.next(res);
    console.log('ERROR', res)
    // this.snackBar.open(`${res.message}`, 'Hide', {duration:10000, horizontalPosition: 'right', panelClass:['error-snack']})
    let notification = new Notification(1, 'error', 'HELLO KITTY')
    this.notificationService.addNotification(notification)

    return observableThrowError(res);
  }

notification.service:

@Injectable({
  providedIn: 'root'
})
export class NotificationService {
  isOpen : boolean
  private notifications = new Array<Notification>();
  public notificationsSubject: ReplaySubject<Notification[]>;
  constructor(
    private snackBar: MatSnackBar,
  ) { }

  open() {
    this.isOpen=true

  }

  addNotification(notification: Notification) {      

        this.notifications = [...this.notifications, notification];
        console.log('NOTIF', this.notifications)

        this.notificationsSubject.next(this.notifications);
    }

The error occurs in the 'addNotification' function, where this.notificationsSubject is undefined. Can you explain why it is undefined? Thanks

Upvotes: 3

Views: 1268

Answers (1)

Florian Ludewig
Florian Ludewig

Reputation: 6002

You have to initialize notificationsSubject with a default value:

public notificationsSubject: ReplaySubject<Notification[]> = new ReplaySubject({ /* ... */ })

Upvotes: 2

Related Questions