AuthGuard在Angular 4中运行不佳

时间:2017-09-04 13:57:05

标签: angular authentication angular-services angular-http

我需要帮助,因为我在访问应用程序中的某个页面时遇到问题 首先,您需要先登录应用程序才能看到仪表板。问题是,当我放入app-routing.module.ts canActivate: [AuthGuard]中的DashboardComponent时,我无法访问信息中心,但当我删除它时,我可以访问信息中心。也许我的dashboard.component.ts有问题。或者是其他东西?

  

signin.component.ts

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 => {
           this.router.navigate(['dashboard']);
             alert("yeah");
          },
          error => {
             alert("nooo");
             console.log(error);
          });

  }

}
  

AUTH-guard.service.ts

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();
  }
}
  

auth.service.ts

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 => res.json())
    .map((res) => {
      if (res.success) {
        localStorage.setItem('auth_token', res.auth_token);
        this.loggedIn = true;
      }

      return res.success;
    });

   }

   isLoggedIn() {
    return this.loggedIn;
  }
}
  

APP-routing.module.ts

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 {

}
  

dashboard.component.ts

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 => res.json());
  }

}

0 个答案:

没有答案