Redirection inside Angular 2 component

I have a simple method that in the end I want to redirect to another component:

export class AddDisplay{ display: any; addPairTo(name: string, pairTo: string){ this.display = {}; this.display.name = name; this.display.pairTo = pairTo; } } 

What I want to do is redirect at the end of the method to another component:

 export class AddDisplay{ display: any; addPairTo(name: string, pairTo: string){ this.display = {}; this.display.name = name; this.display.pairTo = pairTo; this.redirectTo('foo'); } } 

How to achieve this in Angular 2?

+48
javascript angular
Oct 01 '15 at 20:35
source share
2 answers

configure routing first

 import {RouteConfig, Router, ROUTER_DIRECTIVES} from 'angular2/router'; 

and

 @RouteConfig([ { path: '/addDisplay', component: AddDisplay, as: 'addDisplay' }, { path: '/<secondComponent>', component: '<secondComponentName>', as: 'secondComponentAs' }, ]) 

then in your component import and then enter Router

 import {Router} from 'angular2/router' export class AddDisplay { constructor(private router: Router) } 

the last thing you need to do is call

 this.router.navigateByUrl('<pathDefinedInRouteConfig>'); 

or

 this.router.navigate(['<aliasInRouteConfig>']); 
+63
02 Oct '15 at 9:35
source share

@Kit's answer is fine, but be sure to add ROUTER_PROVIDERS to the providers in the component. Then you can redirect to another page in the ngOnInit method:

 import {Component, OnInit} from 'angular2/core'; import {Router, ROUTER_PROVIDERS} from 'angular2/router' @Component({ selector: 'loginForm', templateUrl: 'login.html', providers: [ROUTER_PROVIDERS] }) export class LoginComponent implements OnInit { constructor(private router: Router) { } ngOnInit() { this.router.navigate(['./SomewhereElse']); } } 
+5
Apr 08 '16 at 8:20
source share