Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 - How do I navigate to another route using this.router.parent.navigate('/about')?

Angular 2 - How do I navigate to another route using this.router.parent.navigate('/about')?

It doesn't seem to work. I tried location.go("/about"); as that didn't work.

Basically, once a user has logged in I want to redirect them to another page.

Here is my code below:

 import {Component} from 'angular2/angular2';  import {CORE_DIRECTIVES, FORM_DIRECTIVES} from 'angular2/angular2';  import {Router} from 'angular2/router';   import {AuthService} from '../../authService';   //Model  class User {    constructor(public email: string, public password: string) {}  }   @Component({    templateUrl:'src/app/components/todo/todo.html',    directives: [CORE_DIRECTIVES, FORM_DIRECTIVES]  })   export class Todo {         model = new User('[email protected]', 'Password');       authService:AuthService;      router: Router;     constructor(_router: Router, _authService: AuthService){           this.authService = _authService;        this.router = _router;    }     onLogin = () => {        this.authService.logUserIn(this.model).then((success) => {                  //This is where its broke - below:                     this.router.parent.navigate('/about');         });    }  } 
like image 665
AngularM Avatar asked Nov 06 '15 16:11

AngularM


People also ask

How do you navigate to a router?

navigate method, you must supply the ActivatedRoute to give the router knowledge of where you are in the current route tree. After the link parameters array, add an object with a relativeTo property set to the ActivatedRoute . The router then calculates the target URL based on the active route's location.

How does router navigate work Angular?

Angular router traverses the URL tree and matches the URL segments against the paths configured in the router configuration. If a URL segment matches the path of a route, the route's child routes are matched against the remaining URL segments until all URL segments are matched.

How do you route from one page to another page in Angular?

You can navigate one to another page in Angular in Two ways. (both are same at wrapper level but the implementation from our side bit diff so.) routerLink directive gives you absolute path match like navigateByUrl() of Router class.

What is difference between navigate and navigateByUrl?

difference between the two navigateByUrl is similar to changing the location bar directly–we are providing the “whole” new URL. Whereas router. navigate creates a new URL by applying an array of passed-in commands, a patch, to the current URL.


1 Answers

Absolute path routing

There are 2 methods for navigation, .navigate() and .navigateByUrl()

You can use the method .navigateByUrl() for absolute path routing:

import {Router} from '@angular/router';  constructor(private router: Router) {}  navigateToLogin() {    this.router.navigateByUrl('/login'); } 

You put the absolute path to the URL of the component you want to navigate to.

Note: Always specify the complete absolute path when calling router's navigateByUrl method. Absolute paths must start with a leading /

// Absolute route - Goes up to root level     this.router.navigate(['/root/child/child']);  // Absolute route - Goes up to root level with route params    this.router.navigate(['/root/child', crisis.id]); 

Relative path routing

If you want to use relative path routing, use the .navigate() method.

NOTE: It's a little unintuitive how the routing works, particularly parent, sibling, and child routes:

// Parent route - Goes up one level  // (notice the how it seems like you're going up 2 levels) this.router.navigate(['../../parent'], { relativeTo: this.route });  // Sibling route - Stays at the current level and moves laterally,  // (looks like up to parent then down to sibling) this.router.navigate(['../sibling'], { relativeTo: this.route });  // Child route - Moves down one level this.router.navigate(['./child'], { relativeTo: this.route });  // Moves laterally, and also add route parameters // if you are at the root and crisis.id = 15, will result in '/sibling/15' this.router.navigate(['../sibling', crisis.id], { relativeTo: this.route });  // Moves laterally, and also add multiple route parameters // will result in '/sibling;id=15;foo=foo'.  // Note: this does not produce query string URL notation with ? and & ... instead it // produces a matrix URL notation, an alternative way to pass parameters in a URL. this.router.navigate(['../sibling', { id: crisis.id, foo: 'foo' }], { relativeTo: this.route }); 

Or if you just need to navigate within the current route path, but to a different route parameter:

// If crisis.id has a value of '15' // This will take you from `/hero` to `/hero/15` this.router.navigate([crisis.id], { relativeTo: this.route }); 

Link parameters array

A link parameters array holds the following ingredients for router navigation:

  • The path of the route to the destination component. ['/hero']
  • Required and optional route parameters that go into the route URL. ['/hero', hero.id] or ['/hero', { id: hero.id, foo: baa }]

Directory-like syntax

The router supports directory-like syntax in a link parameters list to help guide route name lookup:

./ or no leading slash is relative to the current level.

../ to go up one level in the route path.

You can combine relative navigation syntax with an ancestor path. If you must navigate to a sibling route, you could use the ../<sibling> convention to go up one level, then over and down the sibling route path.

Important notes about relative nagivation

To navigate a relative path with the Router.navigate method, you must supply the ActivatedRoute to give the router knowledge of where you are in the current route tree.

After the link parameters array, add an object with a relativeTo property set to the ActivatedRoute. The router then calculates the target URL based on the active route's location.

From official Angular Router Documentation

like image 126
TetraDev Avatar answered Oct 11 '22 15:10

TetraDev