user3353167
user3353167

Reputation: 892

Angular, component subscribed to subject won't receive event

I have a service that is responsible to create a subjectbehaviour and listening for updates. One more component will trigger an event to the behaviour subject, and the last component subscribes to it and pushes the value to the array. Below my implementation so far.

this is my service

private _menuSubject = new BehaviorSubject<MenuList>({
    menu_item_id:null,
    menu_item_category:null,
    menu_item_description:null,
    menu_item_name:null,
    menu_item_price:null
});
menuListObs$: Observable<MenuList> = this._menuSubject.asObservable();
updateMenuArray(item:MenuList):void {
    this._menuSubject.next(item);
}

 getUpdatedMenuArray():Observable<MenuList>{
    return this.menuListObs$;
}

the component that sends the message

onSubmit(menu){
   this.menu.updateMenuArray(menu);
}

and the component that subscribes to the service for an update

ngOnInit() {
    this.menu.getUpdatedMenuArray().subscribe((item)=>{
        this.menuList.push(item)
    });
}

The problem I face is that in my last component the subscriber is not triggered. What am I doing wrong? Thanks in advance

Upvotes: 0

Views: 120

Answers (1)

Benjamin Sch&#228;ublin
Benjamin Sch&#228;ublin

Reputation: 1666

You are triggering the event on the behavioursubject this._menuSubject.next(item); but listen to the event on a old observable-copy of the subject.

Try making _menuSubjectpublic (or return it in a public getter) and subscribe to it directly. You may want to skip the first item, because the first would be the current value.

Upvotes: 1

Related Questions