canActivate无法正常工作Angular 5

时间:2018-06-30 06:33:49

标签: jwt angular5 angular-routing

我编写了一个角度为5的应用程序用于测试,并在后端使用JWT进行用户身份验证。 我希望未经身份验证的用户无法访问个人资料页面,因此我将CanActivate用于我的路线,但是当我在应用程序中单击“登录”时,没有任何反应。 我用console.log的loginIn值登录后也返回假值。

token.service.ts

import { Injectable } from '@angular/core';

@Injectable()
export class TokenService {

private iss = {
  login: 'http://localhost:8000/api/login',
  signup: 'http://localhost:8000/api/signup'
};

constructor() { }

handle(token) {
  this.set(token);
}

set(token) {
  localStorage.setItem('token', token);
}

get() {
  return localStorage.getItem('token');
}

remove() {
  localStorage.removeItem('token');
}

isValid() {
  const token = this.get();
  if (token) {
    const payload = this.payload(token);
    if (payload) {
      return (Object.values(this.iss).indexOf(payload.iss) > 0) ? true : 
false;
    }
  }

  return false;
}

payload(token) {
  const payload =  token.split('.')[1];
  return this.decode(payload);
}

decode(payload) {
  return JSON.parse(atob(payload));
}

loggedIn() {
  return this.isValid();
  }
}

auth.service.ts:

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { TokenService } from './token.service';

@Injectable()
export class AuthService {

  private loggedIn = new BehaviorSubject <boolean> (this.Token.loggedIn());
  authStatus = this.loggedIn.asObservable();

  changeAuthStatus(value: boolean) {
    this.loggedIn.next(value);
  }

  constructor(private Token: TokenService) { }
}

before-login.service.ts:

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs';
import { TokenService } from './token.service';

@Injectable()
export class BeforeLoginService implements CanActivate {

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean |
    Observable<boolean> | Promise<boolean> {
      return !this.Token.loggedIn();
    }

  constructor(
    private Token: TokenService
  ) { }
}

after-login.servie.ts:

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs';
import { TokenService } from './token.service';

@Injectable()
export class AfterLoginService implements CanActivate {

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean |
    Observable<boolean> | Promise<boolean> {
      return this.Token.loggedIn();
    }

  constructor(
    private Token: TokenService
  ) { }
}

login.component.ts:

import { Component, OnInit } from '@angular/core';
import { JarwisService } from '../../Services/jarwis.service';
import { TokenService } from '../../Services/token.service';
import { Router } from '@angular/router';
import { AuthService } from '../../Services/auth.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  public form = {
    email: null,
    password: null
  };

  public error = null;

  constructor(
    private Jarwis: JarwisService,
    private Token: TokenService,
    private router: Router,
    private Auth: AuthService
  ) { }

  onSubmit() {
    this.Jarwis.login(this.form).subscribe(
      data => this.handleResponse(data),
      error => this.handleError(error)
    );
  }

  handleResponse(data) {
      this.Token.handle(data.access_token);
      this.Auth.changeAuthStatus(true);
      this.router.navigateByUrl('/profile');
  }

  handleError(error) {
    this.error = error.error.error;
  }

  ngOnInit() {
  }

}

jarwis.service.ts:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';

@Injectable()
export class JarwisService {
  private baseUrl = 'http://localhost:8000/api';

  constructor(private http: HttpClient) { }

  signup(data) {
    return this.http.post(`${this.baseUrl}/signup`, data);
  }

  login(data) {
    return this.http.post(`${this.baseUrl}/login`, data);
  }
}

app-routing.module.ts:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import {LoginComponent} from "./components/login/login.component";
import {SignupComponent} from "./components/signup/signup.component";
import {ProfileComponent} from "./components/profile/profile.component";
import {RequestResetComponent} from "./components/password/request-reset/request-reset.component";
import {ResponseResetComponent} from "./components/password/response-reset/response-reset.component";
import { BeforeLoginService } from './Services/before-login.service';
import { AfterLoginService } from './Services/after-login.service';

const appRoutes: Routes  = [
  {
    path: 'login',
    component: LoginComponent,
    // canActivate: [BeforeLoginService]
  },
  {
    path: 'signup',
    component: SignupComponent,
    // canActivate: [BeforeLoginService]
  },
  {
    path: 'profile',
    component: ProfileComponent,
    // canActivate: [AfterLoginService]
  },
  {
    path: 'request-password-reset',
    component: RequestResetComponent,
    // canActivate: [AfterLoginService]
  },
  {
    path: 'response-password-reset',
    component: ResponseResetComponent,
    // canActivate: [AfterLoginService]
  },
  ]

@NgModule({
  imports: [
    RouterModule.forRoot(appRoutes)
  ],
  declarations: [],
  exports: [RouterModule]
})
export class AppRoutingModule { }

0 个答案:

没有答案