user2529173 user2529173 - 10 months ago 70
AngularJS Question

angular2 - Check user login

I'm starting to learn all about angular 2 and currently have a problem. I have defined these routes in my application:

const appRoutes: Routes = [
{path: 'start',
component: StartComponent,
children:[{path: '' },
path:'nested', component:NestedTestComponent
{path: '', component:LoginFormComponent}

There is the "base" path which shows a login form, after the user entered credentials (and they are correct), the user will be directed to "start" and this as a nested route "nested".
This works great. But I want to somehow restrict the user to visit "start" and "nested" if the user is not logged in. Because that's currently possible with just entering this as an url.

My index.html looks like this:



selector: "app-root",
template: `
styleUrls: ['./app.component.css']


<div class="nav-wrapper">
<a href="#" class="brand-logo center"></a>
<ul id="nav-mobile" class="right hide-on-med-and-down">
<li><a (click)="logout()">Logout</a></li>

Since everything is somehow nested in the my approach was to check in the app.component if the user is logged in with this:

export class AppComponent {

constructor(af:AngularFire, router:Router){
if(af.auth.getAuth() == null){
//redirect to start
console.log('redirect to login');
console.log('not redirect to login');

This works and correctly detects if user should be redirected or not. However, the
does not work. It just does nothing.

Answer Source

use CanActivate you can allow user to visit page only if it's has been activated in route or redirect them to login.

import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { CanActivateAuthGuard } from './auth.service'

import { MyComponent } from './app.component';

const routes: Routes = [
    { path: '/home', component: MyComponent , canActivate: [CanActivateAuthGuard]}]

/In auth service/

import { CanActivate, Router } from '@angular/router';

export class CanActivateAuthGuard implements CanActivate {
  constructor(private router: Router) {}
    if (this.authService.isLoggedIn()) {
        return true;
    //Redirect the user before denying them access to this route
    return false;