2016-07-04 115 views
2

我使用Angular 2,SystemJs和ES6(Not TypeScript)。如何从Angular 2调用路由器导航方法?

我想要什么?我想导航到与路线的链接。我在做什么

// route for exam simple 
export let routes = [ 
    {path: '', name: 'home', component: HomeComponent, terminal: true}, 
    {path: 'auth', name: 'auth', component: AuthComponent} 
] 

如果我使用[routerLink],效果很好。现在我想以编程方式使用路由器这样

import { Component } from '@angular/core'; 
import { Router, ROUTER_DIRECTIVES } from '@angular/router'; 

@Component({ 
    selector: 'tf-main', 
    directives: [ROUTER_DIRECTIVES], 
    template: '<p>home</p><router-outlet></router-outlet>' 
}) 

export class HomeComponent { 

    static get parameters() { 
     return [[Router]] 
    } 

    constructor(router) { 
     this.router = router; 

     // This wrong way!!!! Help!!!! 
     this.router.navigateByUrl(['auth']); 
    } 
} 

回答

8

只是

this.router.navigate(['auth']); 

this.router.navigate(['/auth']); 

(确保根路径使用auth

+0

问题是** this.router **没有导航方法 –

+0

您使用的是什么Angular2版本? –

+0

我使用的是Angular 2版本2.0.0.rc4,路由器3.0.0.beta1 –

2

有关使用此构造方法怎么看?

constructor(
private router: Router){} 

然后

ngOnInit() { 
    this.router.navigate(['auth']); 
} 

我认为你的错误消息意味着你应该正确初始化 '路由器'。