angular数据请求 token验证

angualr的token 验证会经常用在登录,注册等地方

对于token的使用方法按照以下步骤进行使用即可

1.新建一个服务 

  ng g service services /+服务名

 egng g service services/player

会在根目录下出现一个叫service的服务文件夹

文件夹中会存在一个player.service,ts和一个player.service,spec.ts

2.在根目录下新建一个文件夹,是用来封装token的写法 

eg: 文件夹的名字为utils

  1. 在文件夹中新建一个名字为token.util.ts的文件
  2. 打开此文件
  3. 在此文件中注入并声明 import {Injectable,BgModule} from '@angular/core'
  4. 声明引入的组件模块 @Injectable()   @NgModule()
  5. 开始进行封装

  export default class TokenUtil{    

    private name:string = 'jwt-token'

     getToken():string {

        return localStorage.getItem(this.name)

     }

     setToken(token:string):void{

      localStorage.setItem(this.name,token)

    }

  }

3.在app目录中新建文件夹http-interceptors
  • 在此文件夹中新建index.ts文件和noop-interceptor.ts文件
  • 在index.ts中写入

    /* "Barrel" of Http Interceptors */

    import { HTTP_INTERCEPTORS } from '@angular/common/http';

    import { NoopInterceptor } from './noop-interceptor';

    /** Http interceptor providers in outside-in order */

    export const httpInterceptorProviders = [

      { provide: HTTP_INTERCEPTORS, useClass: NoopInterceptor, multi: true },

    ];

  • 在noop-inter-interceptor.ts文件中写入
  1. 先引用注入
    import TokenUtil from '../../utils/token.util'
  2. import { AppRoutingModule } from './app-routing.module';
  3. @Injectable()
  4. export class NoopInterceptor implements HttpInterceptor {

      constructor(private tokenUtil: TokenUtil) { }

      intercept(req: HttpRequest<any>, next: HttpHandler)
      {
        // Get the auth token from the service.
        const authToken = this.tokenUtil.getToken();

        // Clone the request and replace the original headers with
        // cloned headers, updated with the authorization.
        const authReq = req.clone({
          headers: req.headers.set('Authorization', `bearer ${authToken}`)
        });

        // send cloned request with header to the next handler.
        return next.handle(authReq);
      }
    }
  • 在app.module.ts中引用和注入新建的一系列文件 TokenUtil 和 httpInterceptorProviders 组件
  • @NgModule中的imports中声明一次 
  1. TokenUtil
  2. ReactiveFormsModule
  • providers中进行一次(使用)
    providers: [httpInterceptorProviders],

4.在对应的组件中ts中进行一次使用 服务引用

   import { PlayerService} from '../../player.service';
 
  constructor(private tokenUtil: TokenUtil, private route: ActivatedRoute)
 
 
 
 
 

猜你喜欢

转载自www.cnblogs.com/rockyjs/p/11857991.html
今日推荐