【问题标题】:Angular 2 routing with custom base href cant find route带有自定义基本href的Angular 2路由找不到路由
【发布时间】:2018-05-15 17:42:15
【问题描述】:

当我手动尝试打开某个页面(通过在浏览器中输入 url)时,我的应用似乎找不到要使用的路径。页面正在加载,但路由器插座为空。我还收到“EmptyError:序列中没有元素”。发现这是 canActivate 方法的一些问题,尝试将 Observables 更改为 Promise,正如这里所说的 EmptyError: no elements in sequence 但仍然出错。

我的应用也有自定义的基本 href,在 index.html 中定义

app.routing.ts

const appRoutes: Routes = [
    {
        path: 'project',
        canActivate: [AuthGuard],
        canActivateChild: [AuthGuard],
        children: [
            {
                path: 'home',
                component: HomeComponent
            },
            {
                path: 'events',
                loadChildren: 'app/feature/events/events.module#EventsModule'
            },
        ],
    }
];

因此,当我尝试转到 "localhost/some/base/href/project/home" 时,我得到了空白页面,只有应用程序的主菜单可见。此外,url 变成了 "localhost/some/base/href" 然后我可以通过单击应用程序主菜单上的按钮来导航我的应用程序(它们的超链接是 'localhost/some/base/href/project/events/列表'例如)。这项工作完美,路线建立。

试图将 appRoutes 中的路径更改为 'some/base/href/project',现在当我转到 "localhost/some/base/href/project/home" em> HomeCompoment 已加载,但 url 变为 "localhost/some/base/href/some/base/href/project/home" 并且应用程序主菜单上的按钮也停止工作.

当然,我可以重定向

path: '**',
redirectTo: '/project/home',
pathMatch: 'full'

但这只会给我主页,我想手动导航到应用程序中的其他组件。

更新: 我的 authGuard,也尝试返回 Observable 和 Promise 但没有效果。 isAuthorized() 现在总是返回 true。

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        let result: boolean = this.authService.isAuthorized();

        if (result) {
            return true;
        }

        this.authService.setRedirectUrl(state.url);

        return false;
    }

【问题讨论】:

  • 你能展示一下守卫是如何实现的吗?
  • @RRForUI 已编辑
  • 如果您将应用程序托管在 IIS 的虚拟目录中,请尝试将 href 标记保留为空。这也许可以使您的网址保持正确。此外,如果您使用服务为守卫返回值,使其返回可观察的,canActivate 应该自动订阅守卫。

标签: angular routing angular2-routing base-url


【解决方案1】:

以这种方式制作路线:

这里我们有主要分支 - LoginRoot 带有空键 - 路径: ''

还有子分支,这些路径包含子页面 - alertsdashboards 等等。

您可以使用 children 字段递归地构建尽可能深的路径。

如果您想手动导航到路线,您需要在 appRoutes 数组中以提供的样式定义所有路径。

const appRoutes: Routes = [
  {path: 'login', component: LoginComponent},
  {path: '', component: MainComponent, redirectTo: '/dashboard', pathMatch: 'full'
    children: [
      { path: 'alert/:id', component: AlertDetailComponent },
      { path: 'alerts', component: AlertsComponent },
      { path: 'dashboard', component: EriskDashboardComponent }
  ]}];

你可以创建一些默认路由来登录/404页面

path: '**',
redirectTo: '/login',
pathMatch: 'full'

另外,需要提一下,那个角度路由器 在路由器中默认使用 哈希符号 - #;

所以要导航到登录,您需要构建这样的路径:

#/login
#/dashboard

http://localhost:4200/#/login

在app.module.ts中可以找到使用hash的设置,当我们导入路由模块时:

imports:[
    RouterModule.forRoot(routes, { useHash: true }),
]

【讨论】:

    猜你喜欢
    • 2016-04-04
    • 1970-01-01
    • 2020-02-12
    • 1970-01-01
    • 2021-05-31
    • 2016-12-27
    • 1970-01-01
    • 2017-08-10
    • 2017-03-04
    相关资源
    最近更新 更多