My Subject is not working properly in Angular

前提是你 提交于 2020-01-25 06:41:07

问题


I've created a subject in service file as usual

editLectures = new Subject<Lecture>();

getEditLectureListener() {
  return this.editLectures.asObservable();
}

From one component I'm sending a data (I am getting proper data when I console.log it)

onUpdate(lec: any) {
  this.attendanceService.emitLecture(lec);
}

On another component I'm listening to the Subject:

this.updateLecture = this.attendanceService.getEditLectureListener().subscribe(result => {
  // my code
  // on console.log(result) i am not getting anything and other listeners
  // are working perfectly, the only difference is that
  // its not emitting data from http response 
});

In service I'm emitting the data:

emitLecture(lec: Lecture) {
  this.editLectures.next(lec);
  this.router.navigate(['edit-lecture']);
}

回答1:


You need to use BehaviorSubject instead of Subject so the last emitted value will be available for new subscriber (when your listener component is instantiated).

editLectures = new BehaviorSubject<Lecture>(null);


来源:https://stackoverflow.com/questions/58935881/my-subject-is-not-working-properly-in-angular

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!