简体   繁体   中英

Angular ngOnInit not working on route share component

I have a component "MenuComponent" that loads a menu when a link is clicked in the sidebar. The "MenuComponent" is child of a "MenusComponent" through <router-outlet></router-outlet> When I click on the menu in the sidebar the link changes to one of the following.

#/cms/menus/1/menus/1
#/cms/menus/1/menus/3
#/cms/menus/1/menus/5
#/cms/menus/1/menus/6

I would like to load the menu and setup some properties whenever the link is clicked. I do this in;

  ngOnInit() {
      let menuid = this.route.snapshot.params.id;
      this.LocalService.PlacementMenus.Activate(menuid);
    this.Initialise();
    this.LocalService.changeMenuComponents('menuList');
      let placementid = this.route.snapshot.params.placementid;
      this.LocalService.AllPlacements.Activate(placementid);
  }

But ngOnInit does not work the second time I click a menu in the sidebar. i see there are other hooks such as;

ngAfterContentInit()
ngAfterViewInit()

But none of these work.

The snapshot is just that, a snapshot at a particular point in time:

this.route.snapshot.params.id;

Use the observable instead. Then it will update each time the parameters change.

    this.route.params.subscribe(
     params => {
        let menuid = +params['id'];
        // OR let menuid = +paramMap.get('id');
        this.LocalService.PlacementMenus.Activate(menuid);
        this.Initialise();
        this.LocalService.changeMenuComponents('menuList');
        let placementid = this.route.snapshot.params.placementid;
        this.LocalService.AllPlacements.Activate(placementid);
     }
  );

For a little cleaner code, you could add all of the above method calls into one method and call that from inside the subscribe.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM