簡體   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