I had a list of children in a school. There was a menu option to filter by class. Clicking the links on the menu, where it would re-route from “/class” to “/class/:className” was just not triggering. I could have used (click) events, but I was restricted by the design parameters. I hate doing an actual “reload” of angular, so a generic link instead of a routerLink was unacceptable.
Once again, a simple task turns into a mess. For some reason, the links just wouldn’t trigger the constructor or the ngOnInit function!
Here’s what I had to do:
- Declare an Observerable in the class. I’ll call it “Observer”.
- Subscribe to the router events: this.myObserver=this.router.events.subscribe((event) => { some stuff });
- ONLY so something after the navigation has ended (there are lots of router events! if (event instanceof NavigationEnd) { some stuff }
- Now you’ve got it so when someone clicks a link, it will trigger that event. So you can reload your dataset right there, redraw things on the page, etc… (all the things I’d expected I could just do in the ngOnInit).
- But, be warned, it doesn’t go away when you leave the page. You HAVE to unsubscribe that observable, otherwise you’ll be reloading that date over and over again throughout the site! So, you need to add OnDestroy to the class events and do a “this.myObserver.unsubscribe();” within it.
selector: 'app-rosters', templateUrl: './rosters.component.html', styleUrls: ['./rosters.component.scss'] }) export class RostersComponent implements OnInit , OnDestroy{ families: any = []; classFilter: string = ""; data: any; myObserver; private _data: BehaviorSubject<any> = new BehaviorSubject<any>([]); constructor( public responsive: ResponsiveService, private dl: DataLayerService, private route: ActivatedRoute, private router: Router) { this.myObserver= this.router.events.subscribe((event) => { console.log("event", event) if (event instanceof NavigationEnd) { this.classFilter = this.route.snapshot.paramMap.get("class") || ''; this.families = []; this.buildRoster(this.data); console.log("rebuild for " + this.classFilter) } }); } ngOnInit() { // this.data = this.getRetVal(); this.dl.getRoster().subscribe(retval => { this.data = retval; this.buildRoster(this.data); }); } ngOnDestroy() { this.myObserver.unsubscribe(); } /* .... rest of the code to build the class rosters commented out */ }