ChatGPT解决这个技术问题 Extra ChatGPT

Angular 2 - 如何使用 this.router.parent.navigate('/about') 导航到另一条路线?

Angular 2 - 如何使用 this.router.parent.navigate('/about') 导航到另一条路线?

它似乎不起作用。我尝试了 location.go("/about");,因为它不起作用。

基本上,一旦用户登录,我想将他们重定向到另一个页面。

下面是我的代码:

 import {Component} from 'angular2/angular2';
 import {CORE_DIRECTIVES, FORM_DIRECTIVES} from 'angular2/angular2';
 import {Router} from 'angular2/router';

 import {AuthService} from '../../authService';

 //Model
 class User {
   constructor(public email: string, public password: string) {}
 }

 @Component({
   templateUrl:'src/app/components/todo/todo.html',
   directives: [CORE_DIRECTIVES, FORM_DIRECTIVES]
 })

 export class Todo {   
     model = new User('Mark@gmail.com', 'Password'); 
     authService:AuthService;
     router: Router;

   constructor(_router: Router, _authService: AuthService){   
       this.authService = _authService;
       this.router = _router;
   }

   onLogin = () => {
       this.authService.logUserIn(this.model).then((success) => {      

          //This is where its broke - below:          
          this.router.parent.navigate('/about');

       });
   }
 }
另外,我在我的 app.ts 文件中设置了路由配置,如下所示:@RouteConfig([ { path: '/', redirectTo: '/home' }, { path: '/home', component: Todo, as : 'Home' }, { path: '/about', 组件: About, as: 'About' } ])
您应该删除路径中的 /,因为它不是必需的

T
TetraDev

绝对路径路由

导航有 2 种方法,.navigate().navigateByUrl()

您可以使用方法 .navigateByUrl() 进行绝对路径路由:

import {Router} from '@angular/router';

constructor(private router: Router) {}

navigateToLogin() {
   this.router.navigateByUrl('/login');
}

您将绝对路径放入要导航到的组件的 URL。

注意:调用路由器的 navigateByUrl 方法时始终指定完整的绝对路径。绝对路径必须以前导 / 开头

// Absolute route - Goes up to root level    
this.router.navigate(['/root/child/child']);

// Absolute route - Goes up to root level with route params   
this.router.navigate(['/root/child', crisis.id]);

相对路径路由

如果要使用相对路径路由,请使用 .navigate() 方法。

注意:路由的工作方式有点不直观,尤其是父路由、兄弟路由和子路由:

// Parent route - Goes up one level 
// (notice the how it seems like you're going up 2 levels)
this.router.navigate(['../../parent'], { relativeTo: this.route });

// Sibling route - Stays at the current level and moves laterally, 
// (looks like up to parent then down to sibling)
this.router.navigate(['../sibling'], { relativeTo: this.route });

// Child route - Moves down one level
this.router.navigate(['./child'], { relativeTo: this.route });

// Moves laterally, and also add route parameters
// if you are at the root and crisis.id = 15, will result in '/sibling/15'
this.router.navigate(['../sibling', crisis.id], { relativeTo: this.route });

// Moves laterally, and also add multiple route parameters
// will result in '/sibling;id=15;foo=foo'. 
// Note: this does not produce query string URL notation with ? and & ... instead it
// produces a matrix URL notation, an alternative way to pass parameters in a URL.
this.router.navigate(['../sibling', { id: crisis.id, foo: 'foo' }], { relativeTo: this.route });

或者,如果您只需要在当前路由路径中导航,但需要导航到不同的路由参数:

// If crisis.id has a value of '15'
// This will take you from `/hero` to `/hero/15`
this.router.navigate([crisis.id], { relativeTo: this.route });

链接参数数组

链接参数数组包含以下用于路由器导航的成分:

到目标组件的路由路径。 ['/英雄']

进入路由 URL 的必需和可选路由参数。 ['/hero', hero.id] 或 ['/hero', { id: hero.id, foo: baa }]

类目录语法

路由器在链接参数列表中支持类似目录的语法,以帮助指导路由名称查找:

./ 或没有前导斜杠相对于当前级别。

../ 在路径路径中上一层。

您可以将相对导航语法与祖先路径结合起来。如果您必须导航到同级路由,您可以使用 ../<sibling> 约定上一级,然后上下同级路由路径。

关于相对导航的重要说明

要使用 Router.navigate 方法导航相对路径,您必须提供 ActivatedRoute 以使路由器知道您在当前路由树中的位置。

在链接参数数组之后,添加一个将 relativeTo 属性设置为 ActivatedRoute 的对象。然后路由器根据活动路由的位置计算目标 URL。

来自官方Angular Router Documentation


请注意,如果您有子路由:{ path: 'home', component: Home, children: homeRoutes } 然后您想将其提供给路由器方法:this.router.navigate(['home/address-search'])this.router.navigateByUrl(/'home/address-search')
即使这是一个很好的答案,重要的是要注意 this.router= Router; 可能会使一些读者感到困惑,在这种情况下提到了路由器的依赖注入,我应该使用此代码而不是 constructor( private router: Router )
@siddharta 感谢您的提示,直到您指出为止,我才注意到这一点。本来应该是写的很快,打算以后更新,但是忘记了。该示例已更新为现在使用正确的依赖注入。
@TetraDev 以及“this.route”从哪里来:D,将其添加到您的依赖项中
L
Luca

你应该使用

this.router.parent.navigate(['/About']);

除了指定路由路径外,您还可以指定路由的名称:

{ path:'/About', name: 'About',   ... }

this.router.parent.navigate(['About']);

嗨,当我这样做时,我在打字稿编译器中收到此错误消息:“'string' 类型的参数不可分配给 any[] 类型的参数,String 类型中缺少属性推送”
我试过了,但没有用:this.router.parent.navigate('[/About]');
您应该使用以下语法: this.router.parent.navigate(['/About']);您必须传递数组 ['/About'] 而不是字符串 '[/About]'
对于路由器 3 测试版,使用 this._router.navigate(['/some-route']);
S
Shaishab Roy

也可以不使用 parent

说路由器定义,如:

{path:'/about',    name: 'About',   component: AboutComponent}

然后可以通过 name 而不是 path 导航

goToAboutPage() {
    this.router.navigate(['About']); // here "About" is name not path
}

针对 V2.3.0 更新

在 v2.0 的路由中,name 属性不再存在。没有 name 属性的路由定义。所以你应该使用 path 而不是 namethis.router.navigate(['/path'])没有前导斜杠 作为路径,所以使用 path: 'about' 而不是 path: '/about'

路由器定义如:

{path:'about', component: AboutComponent}

然后可以通过 path 导航

goToAboutPage() {
    this.router.navigate(['/about']); // here "About" is path
}

Angular 2.0 中的 Route 类型已弃用 name
在 Angular 2 v2.3.0 中,应使用 data 而不是 name。有关更多详细信息 -> angular.io/docs/ts/latest/guide/router.html
s
suresh
import { Router } from '@angular/router';
//in your constructor
constructor(public router: Router){}

//navigation 
link.this.router.navigateByUrl('/home');

虽然此代码段可能是解决方案,但 including an explanation 确实有助于提高帖子的质量。请记住,您正在为将来的读者回答问题,而这些人可能不知道您的代码建议的原因。
Z
ZenAtWork

就个人而言,我发现,由于我们维护了一个 ngRoutes 集合(长篇故事),我从以下方面找到了最大的乐趣:

GOTO(ri) {
    this.router.navigate(this.ngRoutes[ri]);
}

实际上,我将它用作我们面试问题之一的一部分。通过这种方式,我可以通过观察谁在遇到 GOTO(1) 进行首页重定向时的抽搐,几乎可以立即了解谁一直在发展。


这里是不是缺少了什么?