简体   繁体   English

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

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

I use Angular 2, SystemJs and ES6 (Not TypeScript). 我使用Angular 2,SystemJs和ES6(非TypeScript)。

What do I want? 我想要什么? I want navigate to link with Route. 我想导航到与Route连接。 What I'm doing 我在做什么

// route for exam simple
export let routes = [
    {path: '', name: 'home', component: HomeComponent, terminal: true}, 
    {path: 'auth', name: 'auth', component: AuthComponent}
]

It works well if I use [routerLink]. 如果我使用[routerLink],它运行良好。 And now I want programmatically use router like this 现在我想以编程方式使用这样的路由器

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

just 只是

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

or 要么

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

(to ensure the root route auth is used) (以确保使用根路由auth

How about using this constructor? 使用这个构造函数怎么样?

constructor(
private router: Router){}

then 然后

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

I think your error message means you should initialize 'router' correctly. 我认为您的错误消息意味着您应该正确初始化'router'。

According to me router.navigateByUrl accepts only string not array so your syntax should be like this 据我说, router.navigateByUrl只接受字符串而不是数组,所以你的语法应该是这样的

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

or if this is your child route after home th 或者如果这是您回家后的孩子路线

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

see also 也可以看看

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

相关问题 如何调用路由器导航方法而不是routerLink? - How call router navigate method instead of routerLink? Angular:如何在 RouteGuard 中相对于目标路由调用 router.navigate()? - Angular: how to call router.navigate() relative to target route in a RouteGuard? 如何使用角度路由器导航到各个部分? - How to navigate into sections with angular router? 如何使用Angular 2 Router导航到页面的特定部分? - How to navigate to a specific part of the page with the Angular 2 Router? 如何使用 Angular RouterLink 导航到路由器出口? - How to navigate to Router outlet using Angular RouterLink? 如何在Angular 2项目中提供路由器导航功能 - How to provide a router navigate function in Angular 2 project 如何在Angular2路由器中导航到子节点的根? - How to navigate to root of a children in Angular2 router? Angular2路由器:如何导航到某些路径? - Angular2 router: how to navigate to certain path? 如何从Angular测试用例中调用具有Router的构造函数的类的方法? - How to call method of class which has a constructor of Router from Angular test case? 如何开玩笑地模拟 router.navigate 方法 - How to mock the router.navigate method in jest
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM