【问题标题】:How call router navigate method from Angular 2?如何从 Angular 2 调用路由器导航方法?
【发布时间】:2016-07-04 16:31:35
【问题描述】:

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

【问题讨论】:

    标签: angular ecmascript-6 router


    【解决方案1】:

    只是

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

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

    (确保使用根路由auth

    【讨论】:

    【解决方案2】:

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

    constructor(
    private router: Router){}
    

    然后

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

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

    【讨论】:

      【解决方案3】:

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

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

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

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

      另见

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-12-19
        • 2017-04-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-05-05
        相关资源
        最近更新 更多