Search code examples
angularangular5ngrx-store

angular 4 rerouting-component does not reload


I have a component that:

  1. Loads router-outlet into view

  2. In its constructor: Subscribe to an ngrx Store veriable which is initialized already

  3. In its constructor: nevigate to a relevant sub-path/child-component based on that veriable.

ReRoutingComponent.ts

export class ReRoutingComponent implements OnInit {
HOF$:Observable<any>;
HOF:any;

isUHC:boolean;
constructor(
    private _store:Store<any>,
    private _router:Router,
    private _route:ActivatedRoute
) {
    this.HOF$ = _store.select(from_costumer.getHOF);
    this.HOF$.subscribe((v:any)=> {
        this.HOF = v;
        this.isUHC = this.HOF['isUHC'];
        if(this.isUHC) {
            this._router.navigate(['../uscostumer'], {relativeTo: this._route});
        }else {
            this._router.navigate(['../globalcostumer'], {relativeTo: this._route});
        }
    });
}
ngOnInit() {

}
}

So the path domain.com/site/providers re-routes to domain.com/site/providers/globalcostumer by default and to domain.com/site/providers/uscostumer if the ngrx variable was assigned.

Im navigating to domain.com/site/providers using a simple [router-link] directive, not via _router.navigate.

The Problem

  1. When I navigate back to ReRoutingComponent.ts or domain.com/site/providers using the same router-outlet link, The ReRoutingComponent.ts constructor does not run, the component is not reloaded and the ngrx subscription does not re-route to the relevant component.

Solution

  • You can use the ngOnInit lifecycle hook to do these stuffs and it will be called everytime you route to it.

    export class ReRoutingComponent implements OnInit {
    HOF$:Observable<any>;
    HOF:any;
    subscription;
    isUHC:boolean;
    constructor(
        private _store:Store<any>,
        private _router:Router,
        private _route:ActivatedRoute
    ) {}
    
    ngOnInit() {
       this.HOF$ = _store.select(from_costumer.getHOF);
       this.subscription = this.HOF$.subscribe((v:any)=> {
            this.HOF = v;
            this.isUHC = this.HOF['isUHC'];
            if(this.isUHC) {
                this._router.navigate(['../uscostumer'], {relativeTo: this._route});
            }else {
                this._router.navigate(['../globalcostumer'], {relativeTo: this._route});
            }
        });        
    }
    
    ngOnDestroy() {
       this.subscription.unsubscribe();
    }
    
    }