title: AuthGuard Not Working Well in Angular 4
body: <p>I need help since I have a problem accessing a certain page in my application.<br>
  First, you need to login to the app before you can see the dashboard. The problem is that I can't access the dashboard when I put in the <code>app-routing.module.ts</code> the <code>canActivate: [AuthGuard]</code> in the <code>DashboardComponent</code> but when I remove it I can access the dashboard.  Maybe there's a problem on my dashboard.component.ts. Or something else? </p>
  
  <blockquote>
    <p>signin.component.ts</p>
  </blockquote>
  
  <pre class="lang-ts prettyprint-override"><code>import { Component, OnInit } from '@angular/core';
  import { NgForm } from '@angular/forms';
  import { Router, ActivatedRoute } from '@angular/router';
  import { AuthService } from '../auth.service';
  
  @Component({
    selector: 'app-signin',
    templateUrl: './signin.component.html',
    styleUrls: ['./signin.component.css']
  })
  export class SigninComponent implements OnInit {
  
    constructor(private authService: AuthService, 
                private route: ActivatedRoute,
                private router: Router) { }
  
    ngOnInit() {
    }
  
    onSignIn(form: NgForm){
        const email = form.value.email;
        const password = form.value.password;
        this.authService.signinUser(email, password)
        .subscribe(
            data =&gt; {
             this.router.navigate(['dashboard']);
               alert("yeah");
            },
            error =&gt; {
               alert("nooo");
               console.log(error);
            });
  
    }
  
  }
  </code></pre>
  
  <blockquote>
    <p>auth-guard.service.ts</p>
  </blockquote>
  
  <pre class="lang-ts prettyprint-override"><code>import { Router, CanActivate } from '@angular/router';
  import { Injectable } from '@angular/core';
  
  import { AuthService } from './auth.service';
  
  @Injectable()
  export class AuthGuard implements CanActivate {
  
    constructor(private authService: AuthService) {}
  
    canActivate() {
      return this.authService.isLoggedIn();
    }
  }
  </code></pre>
  
  <blockquote>
    <p>auth.service.ts</p>
  </blockquote>
  
  <pre class="lang-ts prettyprint-override"><code>import { Injectable } from '@angular/core';
  import { Http, Headers, Response } from '@angular/http';
  import 'rxjs/add/operator/map';
  
  
  @Injectable()
  export class AuthService {
    private loggedIn = false;
  
    constructor(private http: Http) {
      this.loggedIn = !!localStorage.getItem('auth_token');
    }
  
    signinUser(email: string, password: string) {  
      let headers = new Headers();
      headers.append('Content-Type', 'application/json');
  
      return this.http
      .post(
        'http://example/api/auth/login', 
        JSON.stringify({ email, password }), 
        { headers }
        )
      .map(res =&gt; res.json())
      .map((res) =&gt; {
        if (res.success) {
          localStorage.setItem('auth_token', res.auth_token);
          this.loggedIn = true;
        }
  
        return res.success;
      });
  
     }
  
     isLoggedIn() {
      return this.loggedIn;
    }
  }
  </code></pre>
  
  <blockquote>
    <p>app-routing.module.ts</p>
  </blockquote>
  
  <pre class="lang-ts prettyprint-override"><code>import{ NgModule } from '@angular/core';
  import { Routes, RouterModule, PreloadAllModules } from '@angular/router';
  import { DashboardComponent } from './dashboard/dashboard.component';
  import { SigninComponent } from './auth/signin/signin.component';
  import { AuthGuard } from './auth/auth-guard.service';
  
  const appRoutes: Routes = [
      { path: '', redirectTo: '/signin', pathMatch: 'full' },
      { path: 'signin', component: SigninComponent },
      { path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard]},
  ];
  
  
  @NgModule({
      imports: [RouterModule.forRoot(appRoutes, {preloadingStrategy: PreloadAllModules})
      ],
  
      exports: [RouterModule]
  })
  
  export class AppRoutingModule {
  
  }
  </code></pre>
  
  <blockquote>
    <p>dashboard.component.ts</p>
  </blockquote>
  
  <pre class="lang-ts prettyprint-override"><code>import { Component, OnInit } from '@angular/core';
  import { Injectable } from '@angular/core';
  import { Http, Headers } from '@angular/http';
  
  
  @Component({
    selector: 'app-dashboard',
    templateUrl: './dashboard.component.html',
    styleUrls: ['./dashboard.component.css']
  })
  
  @Injectable()
  export class DashboardComponent implements OnInit {
  
    constructor(private http: Http) { }
  
    ngOnInit() {
      let headers = new Headers();
      headers.append('Content-Type', 'application/json');
      let authToken = localStorage.getItem('auth_token');
      headers.append('Authorization', `Bearer ${authToken}`);
  
      return this.http
        .get('/dashboard', { headers })
        .map(res =&gt; res.json());
    }
  
  }
  </code></pre>