Routing angular 5 , passing a string on params after URL

Issue

I am developing an Angular project based on geographic system information.

The idea is:

  • I have a component which its route is: {path: 'home'}.
  • I want to pass a geojson URL with this route to be like that : {path: 'home/:url'}
  • And in the Onit function of the component I get my URL and use it in a specific function.
  • But the problem that I meet is when I put string I can get it but a long URL it redirect me to the login page.

My code is:

ngOnInit() {
    this.subscription = this.route.params.subscribe(params => {
        this.load(params['url']);
    });
}
 
load (url) {
    // code of the function here
}

Thank you in advance.

Solution

The issue with this implementation is that you are essentially appending your application url with another url. If your routes are defined as /home/:url, you can imagine how confused Angular Router will get if you pass in a geojson URL and your application url suddenly looks like /home/http://geojson.io/#map=13/40.7159/-74.0084 – Router can’t map that url to any defined route and will just navigate to your default/wildcard route (in your case, /login).

A good way to pass long strings around is to set the url as a queryParam instead of a route param — https://alligator.io/angular/query-parameters/.

I suggest removing the /home/:url route and giving something like this a try:

// in your template
<a [routerLink]="['/home']"
   [queryParams]="{ url: 'http://geojson.io/#map=13/40.7159/-74.0084' }">

// in your component
constructor(
  private route: ActivatedRoute
) {}

ngOnInit() {
  let url = this.route.snapshot.queryParams.url;
  this.load(url);
}

private load(url: string) {
  // do something with the url...
}

Answered By – Nathan Beck

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published