如何解决无法读取未定义的属性“ next”?

时间:2019-04-22 05:24:16

标签: angular rxjs observable

在API服务中,我想将错误添加到通知中。 在具有绑定的http请求中调用processError方法: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);
    }

该错误发生在未定义addNotification的'this.notificationsSubject'函数中。您能解释一下为什么它没有定义吗?谢谢

1 个答案:

答案 0 :(得分:2)

您必须使用默认值初始化notificationsSubject

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