1

I have my Angular component and a button on it. When I press the button, I trigger an event in which I have:

this.router.navigate('page2')

I know I can pass query parameters inside the url, but I have a list of strings to pass to the new page. Essentially, if I have to open page2 with a single entity to query, I would do:

url.../page2/entity1

But in my case, I want to send to page2 multiple entities, like entity2, entity3, entity4, and I don't want to pass them as query parameters because they could be many, sometimes also 500-1000!

So, what is the best way to pass this elements to another page using the routing? Consider that passing as query parameter a single entity and refreshing the page I don't loose the results, because the query parameters are in the URL and I just reload the page, so I don't want to loose it too in the case I pass more parameters but I don't have them in the URL! Is it possible?

Riki95
  • 706
  • 1
  • 7
  • 16
  • Create a singleton service which would store all your entities. When your route is loaded check for entities to open and open them. Then clear the list – Sergey Aug 05 '19 at 17:44
  • This not solve because if I reload the page, I have no entities and I have to insert it again from the home page. – Riki95 Aug 05 '19 at 17:46
  • Then write them to the `localStorage`. If you don't need to keep it across the sessions then use `sessionStorage`. It's not being cleared on page reload – Sergey Aug 05 '19 at 17:47
  • Possible duplicate of [How do I pass data to Angular routed components?](https://stackoverflow.com/questions/36835123/how-do-i-pass-data-to-angular-routed-components) – Christopher Peisert Aug 05 '19 at 17:53

1 Answers1

0

As mentioned in Angular documentation, https://angular.io/api/router/NavigationExtras, you can use NavigationExtras object to pass additional data as state or queryParams.

You can provide extra parameters in an object, extraParams

import { Router, NavigationExtras } from '@angular/router';
  ...
constructor(private router: Router) { }

let extraParams: NavigationExtras = {
  state: {
      productId: selectedProductId
  } 
};

this.router.navigate(['/products/details'], extraParams);

Parameters passed this way are not visible in url. They are accessible in the destination page using Router.

constructor(private router: Router) {
const currentState = this.router.getCurrentNavigation();
if (currentState && currentState.extras && currentState.extras.state) {
      let productId:string = console.log(currentState.extras.state.productId );
    } 
}
PradnyaK
  • 51
  • 5