警惕如何从auth.service.ts中获取价值(是否登录用户) [英] guard in angular how can I get value from auth.service.ts (user login or not)

查看:46
本文介绍了警惕如何从auth.service.ts中获取价值(是否登录用户)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在history.guard中使用canActivate,如何检查用户是否登录!我管理的值始终返回false!我需要在auth.service中创建一个新功能还是仅在history.guard中进行编辑?有什么办法可以代替使用Subscribe ??

I use canActivate in history.guard and how can I check if the user login or not! the value which I console always return false! Do I need to create a new function in auth.service or just edit in history.guard ? Is there any way instead of using subscribe ??

auth.service.ts

auth.service.ts

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { Subject } from 'rxjs/Subject';
import { ApiService, VERSION, ENDPOINT } from '../api/api.service';
import { Observable, BehaviorSubject } from 'rxjs';

@Injectable()
export class AuthService {

  logger = new BehaviorSubject<Object>(false);
  referralRoute: string;

  constructor(
    private router: Router,
    private api: ApiService
  ) {
  }

  logout() {
    localStorage.removeItem('access-token');
    localStorage.removeItem('uid');
    localStorage.removeItem('client');
    this.redirectToLogin();
    this.logger.next(false);
  }

  postLogin(body: any) {
    this.api.get(['token.json'], {}).subscribe(
      (res: any) => {
        localStorage.setItem('access-token', res['access-token']);
        localStorage.setItem('uid', res['uid']);
        localStorage.setItem('client', res['client']);
        this.logger.next(true);
        this.redirectToPrevStep();
      },
      (err) => {
        this.logger.next(err);
      });
  }

  checkLogin(body: any) {
    this.api.get([VERSION, ENDPOINT.checkLogin], {}).subscribe(
      (res: any) => {
        this.logger.next(true);
      },
      (err) => {
        this.logger.next(err);
      });
  }

  checkUserLogin() {
    const isLogin = !!localStorage.getItem('JWT_TOKEN');
    if (isLogin) {
      this.logger.next(true);
    } else {
      this.logger.next(false);
    }
  }

  subscribeLogger(): Observable<Object> {
    return this.logger.asObservable();
  }

  isAuthenticated() {
    const token = localStorage.getItem('access-token');
    let isAuthenticated: boolean;
    if (this.isTokenInvalid()) {
      localStorage.removeItem('access-token');
      isAuthenticated = false;
    } else {
      isAuthenticated = true;
    }
    return isAuthenticated;
  }

  getUserInfo() {
    const token = localStorage.getItem('access-token');
    // let userInfo = this.jwtHelper.decodeToken(token);
    return  {};
    //   this.jwtHelper.decodeToken(token),
    //   this.jwtHelper.getTokenExpirationDate(token),
    //   this.jwtHelper.isTokenExpired(token)
    // );
  }

  isTokenInvalid() {
    const token = localStorage.getItem('access-token');
    if (!token) {
      return true
    } else {
      // this.api.setHeaders(token);
      return false;
    }
  }

  /**
   * Helper method for set up referral route, enable useful redirect after login
   * @method setRoute
   * @param  {string} route Route as defined in app.routes, eg. /user/1
   */
  setRoute(route: string): void {
    this.referralRoute = route;
  }

  redirectToPrevStep() {
    const route = this.referralRoute ? this.referralRoute : '/';
    this.router.navigateByUrl(route);
  }

  redirectToLogin(current: string = '/') {
    // Store current url as referral and use latter for login redirection
    this.setRoute(current);
    window.scroll(0, 0);
    this.router.navigate(['/auth/login']);
  }

}

history.guard.ts

history.guard.ts

import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { AuthService } from '../../core/service/auth/auth.service';

@Injectable({ providedIn: 'root' })
export class HistoryGuard implements CanActivate {
  checkUserLogin: boolean;
    constructor(
        private router: Router,
        private auth: AuthService
    ) {}
    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        const checkUserLogin = this.auth.subscribeLogger().subscribe(
          (data: any) => {
            this.checkUserLogin = data;
          }
        );
        if (!this.checkUserLogin) {
          return this.router.navigate(['mypage']);
        }
        else {
          return this.checkUserLogin;
        }
    }
}

history.module.ts

history.module.ts

import { NgModule } from '@angular/core';
import { HistoryComponent } from './history.component';
import { HistoryItemComponent } from './history-item/history-item.component';
import { RouterModule, Routes } from '@angular/router';
import { CommonModule } from '@angular/common';
import { HistoryGuard } from  './history.guard';

const routes: Routes = [
  {
    path: '',
    component: HistoryComponent,
    canActivate: [HistoryGuard]
  },
  {
    path: ':id',
    component: HistoryItemComponent,
    canActivate: [HistoryGuard]
  }
];

@NgModule({
  imports: [
    CommonModule,
    RouterModule.forChild(routes)
  ],
  declarations: [HistoryComponent, HistoryItemComponent]
})
export class HistoryModule { }

推荐答案

您好,我如何实现 AuthGuard ,您可以检查本地存储中是否是JWT令牌,因为注销后应该从 localStorage 中删除jwt令牌,就是这样

Hi this how I implemented AuthGuard, you can check just if in local storage is a JWT token or not, because on logout you should delete jwt token from localStorage and that's it

export class AuthGuard implements CanActivate {
  constructor(private authService: AuthService, private router: Router) {}

  canActivate(): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    if (this.authService.isLoggedIn()) {
      return true;
    } else {
      this.router.navigate(['/login']);
      return false;
    }
  }
}

// Auth service 

isLoggedIn() {
    return Boolean(this.getToken());
}

getToken() {
    return this.localStorage$.retrieve('authenticationToken');
}

logout() {
    this.localStorage$.clear('authenticationtoken');
}

这篇关于警惕如何从auth.service.ts中获取价值(是否登录用户)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆