这是一个可以玩的玩家:
https://plnkr.co/edit/qTjftING3Hk2fwN36bQa?p=preview
一切正常,除非您手动 更改网址栏中的id参数 ,因为项目下拉列表不会将新的projectId显示为当前项目。当用户将网址保存为收藏链接并将其复制/粘贴到网址栏时,会发生这种情况!我会说一个常见的案例!
要解决此问题,我可以在TestsListComponent
中收听route.params更改,并在该下拉菜单中添加sharedService/EventEmitter
更改ID的检查。 TestsListComponent中的bool返回值existsProjectId决定我应该重定向到/projects
页面,因为id不存在。
但老实说,至少从用户体验的角度来看,从TestsListComponent
重定向太迟了,因为route projects/:id/tests
已经被激活了。
你如何解决这种不当行为?
P.S。
也许有一种全局参数更改我可以听,并检查ProjectsListComponent中的路径及其ID,这会有所帮助!
如果有人知道如何在窗口模式下编辑plunkr的url栏以测试该不一致,请告诉我你是如何使该readonly url栏可编辑的...甚至将url复制到新标签中也不会工作,因为我得到一个没有发现错误的plunkr ... => 的 ANSWER
答案 0 :(得分:1)
更新您的app.routes.ts文件,如下所示,并使用HashLocationStrategy作为参考:HashLocationStrategy
import {Routes, RouterModule} from '@angular/router';
import ProjectListComponent from './projects-list.component';
import TestsListComponent from './tests-list.component';
import OverviewComponent from './overview.component';
import {LocationStrategy, HashLocationStrategy} from '@angular/common';
export const routes: Routes = [
{ path: '', redirectTo: 'projects', pathMatch: 'full' },
{
path: 'projects', component: ProjectListComponent,
children: [
{ path: ':id', redirectTo: ':id', pathMatch: 'full' },
{
path: ':id', component: OverviewComponent,
children: [
{ path: '', redirectTo: 'tests', pathMatch: 'full' },
{ path: 'tests', component: TestsListComponent },
]
]
}
];
export const appRoutingProviders: any[] = [
{
provide: LocationStrategy,
useClass: HashLocationStrategy
}
];
export const routing = RouterModule.forRoot(routes);
答案 1 :(得分:0)
没有可以订阅的全局参数更改。
一种方法是从根路由器开始定位路由及其参数:
console.log('router', this.router.routerState.root.firstChild.firstChild && this.router.routerState.root.firstChild.firstChild.snapshot.params);
这可以在this.router.events.subscribe((val) => {
内或路由器保护中完成,例如canActivate
或resolve
https://angular.io/docs/ts/latest/guide/router.html#!#guards
答案 2 :(得分:0)
我不确定我是否正确理解了您的问题,无论如何,这是plunkr。
this.router.events.subscribe(event => {
if (event instanceof RoutesRecognized)
{
var first=event.state.root.firstChild.firstChild;
var id = first && event.state.root.firstChild.firstChild.params['id'];
console.debug('recognized', id);
this.currentProject = this.projects[+id-1];
console.log(this.currentProject);
}
});
只需导航至#/projects/1/tests
。