2016-07-04 118 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']); 
} 

我認爲你的錯誤消息意味着你應該正確初始化 '路由器'。