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('Mark@gmail.com', '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');
});
}
}
Best Answer
Absolute path routing
There are 2 methods for navigation,
.navigate()
and.navigateByUrl()
You can use the method
.navigateByUrl()
for absolute path routing: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/
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:
Or if you just need to navigate within the current route path, but to a different route parameter:
Link parameters array
A link parameters array holds the following ingredients for router navigation:
['/hero']
['/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 theActivatedRoute
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 theActivatedRoute
. The router then calculates the target URL based on the active route's location.From official Angular Router Documentation