如何从Angular 2调用路由器导航方法?

时间:2016-07-04 16:31:35

标签: angular ecmascript-6 router

我使用Angular 2,SystemJs和ES6(非TypeScript)。

我想要什么?我想导航到与Route连接。我正在做什么

// 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']);
    }
}

3 个答案:

答案 0 :(得分:9)

只是

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

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

(确保使用根路由auth

答案 1 :(得分:2)

使用这个构造函数怎么样?

constructor(
private router: Router){}

然后

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

我认为您的错误消息意味着您应该初始化路由器&#39;正确。

答案 2 :(得分:1)

据我说router.navigateByUrl只接受字符串而不是数组,所以你的语法应该是这样的

this.router.navigateByUrl('/auth');

或者如果这是您回家后的孩子路线

this.router.navigateByUrl('/home/auth');

另见