Search code examples
angularobservablestorengrxbehaviorsubject

Angular, accessing router params in a service


We have a menu object (menu store) that several components will use to populate data.

when loading a page I would like to have the menu loaded from server and expose it as a store

private subject = new BehaviorSubject<Menu>(state);
private menuStore = this.subject.asObservable().filter((m) => m != undefined).distinctUntilChanged();

Then each component get the result

    menu$ = this.menuStore.select<MenuItem>('menu');

So the question I have is this... Currently we do actions in the constructor of our "menuService". As i understand it this is not really best practice as it's not under Angulars control(?).

So how should we do this? Should we use "implements OnInit" in the menu.store.ts? or is it valid and ok to do this in the constructor and might this give us problems down the road?


Solution

  • I ended up creating "PageComponents" and in those components subscribing

    this.route.params.subscribe((params: Params) => {
      this.menuService.setActiveItem(params.id)
    })