Angular 2 Login Module with template

2019-09-07 01:55发布

问题:

I have now

One AppModule which has a number of components and one AppCompoennt which is the template componnet with the router-outlet directive.

I want in some way create an AuthModule which has its own template AuthComponent between Login, Register Components.

  1. When user has logged in

  2. it should navigate to the HomeComponent which is rendering in the AppComponent in AppModule.

  3. And now the AppComponent is used as long the user is logged in. When user logout.

  4. It should navigate back to AuthModule.

It is possible to have two template compoents and navigate between them?

回答1:

This is not so difficult. All you need is a parent component which is usually the AppComponent. Inside of the AppComponent you have your main router-outlet. And this router-outlet loads either the LoginComponent or the Component that is only for the users available who are logged in.

This could be your router configuration of your root AppComponent:

{
    path: 'login',
    component: LoginComponent,
    canActivate: [AuthenticationGuard]
},
{
    path: 'app',
    canActivate: [AuthenticationGuard],
    component: HomeComponent,
    children: [
        ...
    ]
}

Inside your router configuration you can use CanActivate. CanActivate is a guard that checks if the user has the permission to navigate to a route/component of your application.

In the example above the AuthenticationGuard checks if the user is logged in or not. So now you can protect your application with this guard. If the guard gets the information that you are logged in it can navigate you automatically to the HomeComponent.

See this guard as an example to protect your HomeComponent from unauthorized users:

@Injectable()
export class LoggedInGuard implements CanActivate {
    constructor(private loginService: LoginService, private router: Router) { }

    canActivate() {
        if (this.loginService.isLoggedIn() !== true) {
            this.router.navigate(['/login']);
            return false;
        } else {
            return true;
        }
    }
}

If the guard returns true, that means that the router will navigate to the specified route. If it returns false, the router protect the route by redirecting the user to the login page.


So now your are switching between both components of the AppComponent's router-outlet. In the HomeComponent you should create another router-outlet if you want to have more then one component for your application. You define these components as the childcomponents of the HomeComponent.

To sum it up:

  • AppComponent -> switch between Login and Home component

  • HomeComponent -> all contents and components that should be protected

So you can see the HomeComponent as the root component of the part of your application that is protected.