繁体   English   中英

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

[英]How call router navigate method from Angular 2?

我使用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']);
    }
}

只是

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

要么

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

(以确保使用根路由auth

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

constructor(
private router: Router){}

然后

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

我认为您的错误消息意味着您应该正确初始化'router'。

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

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

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

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

也可以看看

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM