问题
I am using angular 4 for my app and I use behaviorSubject to communicate between component, everythings were working fine
Here is my code:
export class Globals {
loadStudentsByClass: BehaviorSubject<string> = new BehaviorSubject<string>(null);
}
export class ClassComponent implements OnInit {
selectNewClass() {
console.log('About to select new class', this.selectedClass);
this.globals.loadStudentsByClass.next(this.selectedClass);
this.globals.changeClassBehavior.next(true);
this.router.navigateByUrl('');
}
}
export class StudentComponent implements OnInit {
this.globals.loadStudentsByClass.subscribe(value => {
if (!isNullOrUndefined(value) && this.selectedClass !== value) {
console.log('loadStudentsByClass=> home');
this.loadStudentsByClass(this.selectedClass);
}
});
}
So, I have the component ClassComponent
who triggers the StudentComponent
to call the function loadStudentsByClass
.
This is the only place where I call this behavior subject, but I find my behavior Subject emitted more than once
The problem is why behaviorSubject execute loadStudentsByClass
more than once although this.globals.loadStudentsByClass.next(this.selectedClass);
is called only one time
By the way the number of execution depends on the numbers of views I visited in the application
回答1:
You probably forgot to unsubscribe in your StudentComponent when the components gets destroyed. Save the subscription in a class variable and in ngOnDestroy()
lifecycle hook call subscription.unsubscribe()
回答2:
This will call twice, because whenever the behaviourSubject changes it will emit the latest values. Previously it was null (as default value) which you have given it and next when the service response came you are doing next so it will emit the latest value after change, which is fair enough. For your code you should only check for
if(value){// do the stuff here}
回答3:
Try a replay subject that has no initial value but will still cache your stream:
export class Globals {
loadStudentsByClass = new ReplaySubject<string>(1);
}
来源:https://stackoverflow.com/questions/51403138/behaviorsubject-is-executed-more-than-once