Angular2 - router-outlet with login structure

大兔子大兔子 提交于 2019-12-03 04:46:06

I succeed achieving this workflow by implementing this structure. I have two main components:

LoginComponent which it's route is '/login'. HomeComponent which it's route is ''. (empty route).

In addition I set a guard for my HomeComponent which checks if the user is authenticated in his canActivate. If no I navigates the user to the '/login' route.

Then in my home component I have template with the following structure: tool-bar, side-menu, and router-outlet.

The last thing I have to do is to configure other app routes as children routes of my HomeComponent. (for example: '/news' is a child route of '').

First of all, I highly recommend utilizing the updated Angular2 router. The newest router includes support for guards which are added to your route configuration to prevent access to certain routes.

After ensuring you have the latest router, you'll need to do several things:

1) Create a top-level component and call this App. This is where your <router-outlet> will go.

2) Create a Login component. This component should include a form for logging in to your application, along with the logic for handling login. Create a route for this component.

3) Create a Home component (you have already done this).

4) Use a guard (new functionality in the latest router) to prevent users from accessing the home component before logging in.

Your code will look something like this (for more info, see: https://medium.com/@blacksonic86/upgrading-to-the-new-angular-2-router-255605d9da26#.n7n1lc5cl)

// auth-guard.ts
import { Injectable } from '@angular/core';
import {
  CanActivate,
  Router,
  ActivatedRouteSnapshot,
  RouterStateSnapshot
} from '@angular/router';

import { AuthService } from './services/auth/auth.service';

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private authService: AuthService, private router: Router) {}

  canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    if (this.authService.isLoggedIn()) {
      return true;
    }

    this.router.navigate(['login']);
    return false;
  }
}

For more information on guards:

I would also highly suggest reading up on the latest Angular router (the docs have recently been updated): https://angular.io/docs/ts/latest/guide/router.html

The key is using child routes

import { RouterModule, Route } from '@angular/router';

const ROUTES: Route[] = [
  { path: 'home', component: HomeComponent },
  { path: 'notes',
    children: [
      { path: '', component: NotesComponent },
      { path: ':id', component: NoteComponent }
    ]
  },
];

@NgModule({
  imports: [
    RouterModule.forRoot(ROUTES)
  ]
})

see more here the-three-pillars-of-angular-routing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!