问题
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