Search code examples
angularangular2-routing

Angular 2. Calling a component and getting the parameter works one time only


I have a route defined like this:

{
        path: 'manageagreements', component: ManageagreementsComponent,
        children: [
          { path: 'editagreement/:agreement', component: EditagreementComponent },
        ]
      }

And Im trying to get the parameter Agreement, which I do just fine with the following code:

ngOnInit(): void {
    this.activatedRoute.params.subscribe(parameter => {
      this.agreement = parameter.agreement;
    })
    alert(this.agreement)
  }

At manageagreements.component I have two buttons, for passing the parameters tos and pp.

This works fine when I call the component from its parent for the first time, as follows:

http://localhost:4200/platform/manageagreements/editagreement/tos

But when It is already rendered, and I call it back from the parent component, with a different parameter, it just doesn't work:

http://localhost:4200/platform/manageagreements/editagreement/pp

I don't know what I'm doing wrong, I will appreciate your help.

Thanks.


Solution

  • If anyone is looking for a solution to this issue, you can change the routeReuseStrategy directly at the component level with:

    this.router.routeReuseStrategy.shouldReuseRoute = () => false;
    

    So the code ends up like this (for the example above):

    public agreement: string;
      constructor(
        private activatedRoute: ActivatedRoute,
        private router: Router,
      ) { 
        this.router.routeReuseStrategy.shouldReuseRoute = () => false;
        this.activatedRoute.params.subscribe((params: Params) => {
          this.agreement = params.agreement;
        });
        alert(this.agreement)
      }
    

    Thanks.