Angular 2 router.navigate

JavascriptAngularAngular2 Routing

Javascript Problem Overview


I'm trying to navigate to a route in Angular 2 with a mix of route and query parameters.

Here is an example route where the route is the last part of the path:

{ path: ':foo/:bar/:baz/page', component: AComponent }

Attempting to link using the array like so:

this.router.navigate(['foo-content', 'bar-contents', 'baz-content', 'page'], this.params.queryParams)

I'm not getting any errors and from what I can understand this should work.

The Angular 2 docs (at the moment) have the following as an example:

{ path: 'hero/:id', component: HeroDetailComponent }

['/hero', hero.id] // { 15 }

Can anyone see where I'm going wrong? I'm on router 3.

Javascript Solutions


Solution 1 - Javascript

If the first segment doesn't start with / it is a relative route. router.navigate needs a relativeTo parameter for relative navigation

Either you make the route absolute:

this.router.navigate(['/foo-content', 'bar-contents', 'baz-content', 'page'], this.params.queryParams)

or you pass relativeTo

this.router.navigate(['../foo-content', 'bar-contents', 'baz-content', 'page'], {queryParams: this.params.queryParams, relativeTo: this.currentActivatedRoute})

See also

Solution 2 - Javascript

import { ActivatedRoute } from '@angular/router';

export class ClassName {
  
  private router = ActivatedRoute;

    constructor(r: ActivatedRoute) {
        this.router =r;
    }

onSuccess() {
     this.router.navigate(['/user_invitation'],
         {queryParams: {email: loginEmail, code: userCode}});
}

}

Get this values:

ngOnInit() { this.route .queryParams .subscribe(params => { let code = params['code']; let userEmail = params['email']; }); }

Ref: https://angular.io/docs/ts/latest/api/router/index/NavigationExtras-interface.html

Solution 3 - Javascript

As simpler as

import { Router } from '@angular/router';

constructor( private router:Router) {}

    return(){this.router.navigate(['/','input']);}

Here you will be redirecting to route input . If you wish to go to particular path with relative to some path then.

return(){this.router.navigate(['/relative','input']);}

Here on return() is the method we will be triggered on a button click

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSpaceBeersView Question on Stackoverflow
Solution 1 - JavascriptGünter ZöchbauerView Answer on Stackoverflow
Solution 2 - Javascriptyala rameshView Answer on Stackoverflow
Solution 3 - JavascriptShivaram TolanurView Answer on Stackoverflow