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)
 
 
 
 
 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM