[英]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.