Reload the component with different route parameters in angular

I am using angular2 routing. When the user re-enters a value in the search box and clicks on search, the same component needs to be reloaded, but with different route parameters.

<button (click)="onReload()">Search</button>

onReload() {
this.router.navigate(['results',this.location]);
}

      

This is my route for my ResultsComponent

{ path:'results/:location', component:ResultsComponent}

      

This function changes the url but does not initialize the component.

In angularjs, ui-router I could achieve it like this.

$state.go($state.current, location, {reload: true});

      

How can I do this in angular4?

+3


source to share


3 answers


You need to execute the initialization logic in the subscription callback function in the subscribe callback function of the tracked routes stream.

In your component class

@Component({
  ...
})
export class MyComponent implements OnInit {

   myLocation:string;

   constructor(private route:ActivatedRoute) {}

   ngOnInit() {
     this.route.params.subscribe((params:Params) => {
        this.myLocation = params['location'];
        // -- Initialization code -- 
        this.doMyCustomInitialization();
     }
   }

   private doMyCustomInitialization() {
       console.log(`Reinitializing with new location value ${this.location}`);
   }
}

      



Other times, if you need to allow data based on the "location" value, you must use a security resolution mechanism that allows the data before the component is created. See https://angular.io/guide/router#resolve-guard for more information on configuring security and routing.

This is where plunkr works. https://plnkr.co/edit/g2tCnJ?p=preview

+1


source


edited

The angular way to tell the router to do it is to use onSameUrlNavigation from angular 5.1

But I had to solve this problem in a different way ( Stackblitz ), from subscribing

before route events

and actually calling custom reInit method

.

The trick is to add all subscriptions to the same object and then unsubscribe ONLY when ngOnDestroy

angular is called and the rest of your templates change from custom destroy method

...



    public subscribers: any = {};

    constructor(private router: Router) {
    /** 
      * This is important: Since this screen can be accessed from two menu options 
      * we need to tell angular to reload the component when this happens.
      * It is important to filter the router events since router will emit many events,
      * therefore calling reInitComponent many times wich we do not want.
      */   
      this.subscribers._router_subscription = this.router.events.filter(evt => evt instanceof NavigationEnd).subscribe((value) => { 
        this.reInitComponent();
      });
    }

    reInitComponent() {
        this.customOnDestroy();
        this.customOnInit();
    }

    customOnInit() {
        // add your subscriptions to subscribers.WHATEVERSUB here
        // put your ngOnInit code here, and remove implementation and import 
    }

    customOnDestroy() {
      // here goes all logic to re initialize || modify the component vars  
    }

    /**
     * onDestroy will be called when router changes component, but not when changin parameters ;)
     * it is importatn to unsubscribe here
     */
     ngOnDestroy() {  
       for (let subscriberKey in this.subscribers) {
          let subscriber = this.subscribers[subscriberKey];
          if (subscriber instanceof Subscription) {
            subscriber.unsubscribe();
          }
        }
     }

      

Note that if you implement the necOnInit hook file, you must remove it and implement your own method as in the example.

I added a method unsubscription

because of this angular. angular should actually automatically unsubscribe from router.events when the component is destroyed, but since it isn't, unless you manually unsubscribe you end up making HTTP requests (for example) as many times as you injected the component.

+1


source


https://angular-2-training-book.rangle.io/handout/routing/routeparams.html

In your component, you need to subscribe to the parameters to determine if they have changed.

0


source







All Articles