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

3
我使用Angular 2、SystemJs和ES6(不是TypeScript)。
我想要什么?我希望能够通过路由导航到链接。我的做法是:
// 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个回答

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

(确保使用根路由auth


问题是 this.router 没有导航方法。 - Kirill Muchow
你使用的是哪个Angular2版本? - Günter Zöchbauer
我使用的是Angular 2版本2.0.0.rc4,路由器3.0.0.beta1。 - Kirill Muchow
抱歉,不知道。https://angular.io/docs/js/latest/api/router/index/Router-class.html#!#navigate-anchor - Günter Zöchbauer

5
使用这个构造函数怎么样?
constructor(
private router: Router){}

那么

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

我认为你的错误信息意味着你应该正确地初始化“路由器”(router)。

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接