angular / angular-cli

CLI tool for Angular
https://cli.angular.io
MIT License
26.75k stars 11.98k forks source link

error Guarding Routes in angular cli #3954

Closed juanfarBSU closed 7 years ago

juanfarBSU commented 7 years ago

OS?

os: linux x64 Ubuntu 16.04

Versions.

angular-cli: 1.0.0-beta.24 node: 7.2.0 npm: 3.10.9

Hello, I created a project in cli angular, but the problem is that when I update the page the current route is broken, that happens when I use CanActivate in the paths of my routes, I could not use it and it works, but I have to protect the routes.

Any idea how to solve it ??

This is my code in app.routing.ts

const routes: Routes = [
  { path: '', component: LoginComponent },
  { path: 'reports', component: ReportsComponent, canActivate: [AuthGuard] },
  { path: 'reports/thirds', component: ReportThirdsComponent, canActivate: [AuthGuard] },
  { path: 'reports/profit-loss', component: ReportProfitLossComponent, canActivate: [AuthGuard] },
  { path: 'reports/balance', component: ReportBalanceComponent, canActivate: [AuthGuard] },
];
RicardoVaranda commented 7 years ago

Hi @juanfarBSU , I can confirm that the Guard is working as expected with the cli as I use it in multiple projects. I would recommend you take a look at this guide: https://angular.io/docs/ts/latest/guide/router.html

You seem to be repeating canActivate in multiple paths which does not break the routing but indicated you haven't read the recent guidelines for the router.

There is a couple of example in that Link but most importantly and which will surely meet your needs is the login example.

It should look something like this:

const adminRoutes: Routes = [
  {
    path: 'admin',
    component: AdminComponent,
    canActivate: [AuthGuard],
    children: [
      {
        path: '',
        children: [
          { path: 'crises', component: ManageCrisesComponent },
          { path: 'heroes', component: ManageHeroesComponent },
          { path: '', component: AdminDashboardComponent }
        ],
      }
    ]
  }
];

Do a CTRL+F on the page for: app/admin/admin-routing.module.ts (guarded admin route)

I would recommend you take a look at the guide above that as it explains everything you need to know.

angular-automatic-lock-bot[bot] commented 5 years ago

This issue has been automatically locked due to inactivity. Please file a new issue if you are encountering a similar or related problem.

Read more about our automatic conversation locking policy.

This action has been performed automatically by a bot.