typescript – 如何使用angular2中的链接参数数组从子组件导航到
我的AppComponent有一个@RouteConfig装饰器,用于定义顶级路径:
@RouteConfig([ { path: '/',name: 'Home',component: HomeComponent },{ path: '/about',name: 'About',component: AboutComponent },{ path: '/profile/...',name: 'Profile',component: ProfileComponent } ]) export class AppComponent { } 我的ProfileComponent有一个@RouteConfig装饰器,用于定义Profile子路径: @RouteConfig([ {path: '/',component: ProfileDetailsComponent,name: 'View',useAsDefault: true},{path: '/:id',name: 'Public'},{path: '/edit',component: ProfileEditorComponent,name: 'Edit'},]) export class ProfileComponent { } 当我在ProfileDetailsComponent中时,我可以重定向到其他Profile路由但不能重定向到其他路由.我想避免使用navigateByUrl指定url并使用navigate来改为使用路由名称.例如.: this.router.navigate(['View']); // Works this.router.navigate(['About']); // Raises error that it does not exist 我在这里读到这个答案:Angular 2 – How to navigate to another route using this.router.parent.navigate(‘/about’) 它用: this.router.parent.navigate(['About']); 这有点好,但只有当我在申报时知道重定向应该去的时候才能解决我的问题.我有多个级别的嵌套,并在运行时确定目标路由.我正在寻找一种方法来做类似的事情: this.router.navigate(['Level1','Level2','Level3']); 这允许我在某处跟踪目标路线的完全限定名称.这有可能吗? 解决方法
这是一个微服务派上用场的地方,请查看
service docs here.这个想法是父母可以监听孩子的导航请求,孩子可以根据需要广播所说的变化.
让我们从一个简单的对象开始,它将存储路由名称和可选参数: export class NavArgs { constructor(routeName: string,args?: any) { } } 现在让我们定义微服务,使用 import { Injectable } from '@angular/core' import { Subject } from 'rxjs/Subject'; @Injectable() export class NavigationService { private navigationRequestedSource = new Subject<string>(); onNavigationRequested$= this.navigationRequestedSource.asObservable(); requestNaivation(navArg: string) { this.navigationRequestedSource.next(mission) } } 现在,子组件可以使用它并请求导航: export class SomeChild { constructor(navService: NavigationService) { } invoke() { this.navService.requestNaivation(new NavArgs('SomeRoute')); } } 并且父组件可以侦听所述请求并对其执行操作: export class SomeParent { constructor(navService: NavigationService,router: Router) { this.navService .onNavigationRequested$ .subscribe((navArgs: NavArgs) => { if (navArgs) { if (navArgs.args) { this.router.navigate([ navArgs.routeName,navArgs.args ]); } else { this.router.navigate([ navArgs.routeName ]); } } }); } } 显然这是最基本的代码示例,需要更多的导入和错误处理等.但希望你能得到这个想法. 注意 确保父服务器和子服务器都使用此服务的相同实例非常重要,以便这样做 – 您必须将其设置为使用它的最高级别的提供程序.这是因为默认情况下,Angular2为DI创建单例并使用分层方法.您必须确保不要错误地将其设置为较低级别的提供程序,否则它将无法正常工作. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- Angular 2 中的 ViewChildren 和 ContentChildren
- twitter-bootstrap – Knockout Twitter Bootstrap Popover
- axis-WebService传递复杂对象类型参数
- Bash别名查询
- 用shell脚本实现监控程序自动重启
- AngularJS 精妙绝伦的控制器
- kubectl bash完成在ubuntu docker容器中不起作用
- 使用docker容器中的java访问类路径中的JSON文件时遇到FileN
- BootStrap Table后台分页时前台删除最后一页所有数据refres
- webpack AngularCompilerPlugin hostReplacementPaths选项不