手动更改路由参数会导致用户界面不一致

时间:2017-01-04 22:52:45

标签: angular angular2-routing angular2-services angular2-router3

这是一个可以玩的玩家:

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。

3 个答案:

答案 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) => {内或路由器保护中完成,例如canActivateresolve 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