Tuesday, April 3, 2018

The .subscribe off of params in Angular 4 routing will rerun its guts whenever a route changes!

This...

ngOnInit(): void {
   this.currentPlanType = (!!this.activatedRoute.snapshot.params[this.typeConstant] ?
         this.activatedRoute.snapshot.params[this.typeConstant] : this.individual);
   this.store.dispatch(new SetPlanTypeAction(this.currentPlanType));
}
 
ngOnChanges(): void {
   if (this.currentPlanType) {
      this.activatedRoute.params.subscribe((parameters: Params) => {
         const currentPlanTypeState = (parameters[this.typeConstant]);
         if (currentPlanTypeState !== this.currentPlanType) {
            this.currentPlanType = currentPlanTypeState;
            this.store.dispatch(new SetPlanTypeAction(this.currentPlanType));
         }
      });
   }
}
 
switchPlan(switchState: boolean) {
   const newPlanType = (this.currentPlanType === this.team) ? this.individual : this.team;
   this.router.navigate([this.whereToReroute, newPlanType], { relativeTo:
         this.activatedRoute });
}

 
 

...may just be simplified to this:

ngOnInit(): void {
   this.activatedRoute.params.subscribe((parameters: Params) => {
      const currentPlanTypeState = (parameters[this.typeConstant]);
      if (currentPlanTypeState !== this.currentPlanType) {
         this.currentPlanType = currentPlanTypeState;
         this.store.dispatch(new SetPlanTypeAction(this.currentPlanType));
      }
   });
}
 
switchPlan(switchState: boolean) {
   const newPlanType = (this.currentPlanType === this.team) ? this.individual : this.team;
   this.router.navigate([this.whereToReroute, newPlanType], { relativeTo:
         this.activatedRoute });
}

No comments:

Post a Comment