首页 文章

Angular2路由在每个URL上进行登录

提问于
浏览
0

在我们的应用程序中,我们有多个路由定义 . 而且我认为我们搞砸了什么 . We are unable to write a url by hand and get the proper component to be loaded. We are every time redirected to /login which then redirects back to /account if user is logged in .

您是否看到我们的路由有一些可能的改进?我想这不是很有效率和“做得好” . 我们的大脑被我们自己的路由路径烧毁,外部观点将受到赞赏 .

Secret是我们的核心应用程序,我们只需向用户显示一个秘密请求表单 .

For example, trying to access /account/secret/terms redirects us to login then back to account because the user is currently logged in...

这是我们的路线:

app.routing.ts

import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { LoginComponent } from './login/login.component';
import { AccountComponent } from './account/account.component';

import { accountRoutes } from './account/account.routes';
import { CanActivateViaAuthGuard } from './login/services/auth-guard.service';

const appRoutes: Routes = [
  { path: '', component: LoginComponent },
  { path: 'login', component: LoginComponent },
  {
    path: 'account',
    component: AccountComponent,
    canActivate: [CanActivateViaAuthGuard],
    children: accountRoutes
  },

  // otherwise redirect to home
  { path: '**', redirectTo: '/' }
];

export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);

First side question :在''路由上,我们应该重定向到登录而不是直接调用LoginComponent吗?

./account/account-routes.ts

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

import { DashboardComponent } from './dashboard.component';
import { SecretComponent } from './secret/secret.component';

import { secretRoutes } from './secret/secret.routes';

export const accountRoutes: Routes = [
  { path: '', component: DashboardComponent },
  { path: 'secret', component: SecretComponent, children: secretRoutes },

  // otherwise call DashboardComponent
  { path: '**', component: DashboardComponent }
];

最后,

account / secret / secret.routes.ts:

import { Routes } from '@angular/router';
import { SecretFormComponent } from './secret-form.component';
import { SecretTermsComponent } from './secret-terms.component';
import { TermsGuard } from './services/terms-guard.service';

export const secretRoutes: Routes = [
  {
    path: '',
    redirectTo: 'form'
  },
  {
    path: 'form',
    component: SecretFormComponent,
    canActivate: [TermsGuard]
  },
  { path: 'terms', component: SecretTermsComponent }

  // otherwise redirect to form
  { path: '**',  redirectTo: 'form' }
];

1 回答

  • 1

    最有可能的问题是您使用默认的PathLocationStrategy . 这样,当您在浏览器的地址栏中输入路径的直接URL时,它仍然向服务器发出请求,该服务器无法找到您路由时命名的资源(并且正确地如此) . 服务器可能配置为每当找不到资源时重定向到主页 .

    如果切换到HashLocationStrategy,则不会向服务器发出任何请求,并且在浏览器中输入直接路由URL将起作用 .

    只需将其添加到@NgModule注释中:

    providers:[{provide: LocationStrategy, useClass: HashLocationStrategy}]
    

相关问题