Okay, so I'm aware that this question has been asked multiple times - I've gone through various answers and documentation, but for some reason, I can't seem to get it to work. I just want to confirm that I haven't missed anything.
The scenario is as follows: Two Components, One Service. Both Components need to interact with the Service, with one Component needing to respond when a member of the Service changes.
I have a service with a BehaviorSubject containing a domain object
@Injectable()
export class MyService {
addedMyObject:Subject<MyObject> = new BehaviorSubject();
constructor(private http:Http) {}
getAndAddMyObject(objectId:string) {
this.getMyObject(objectId) // assume this method exists
.subscribe((o) => {
this.addedMyObject.next(o);
});
}
}
I have one component listening for changes on the Service's BehaviorSubject
export class MyFirstComponent() implements OnInit {
constructor(private myService : MyService) {}
ngOnInit() : void {
this.myService.addedMyObject
.subscribe((o) => {
console.log("Incoming object, add to a list or something");
})
}
}
Then, there's a second component that calls the Service to make changes
export class MySecondComponent() {
constructor(private myService : MyService) {}
addSelectedObjectToSomething(objectId) {
this.myService.getAndAddMyObject(objectId);
}
}
However, strangely enough, the subscription in MyFirstComponent isn't triggering. It's really puzzling. What could be the issue?