angualr的token 驗證會經常用在登錄,注冊等地方
對於token的使用方法按照以下步驟進行使用即可
1.新建一個服務
ng g service services /+服務名
eg:ng g service services/player
會在根目錄下出現一個叫service的服務文件夾
文件夾中會存在一個player.service,ts和一個player.service,spec.ts
2.在根目錄下新建一個文件夾,是用來封裝token的寫法
eg: 文件夾的名字為utils
- 在文件夾中新建一個名字為token.util.ts的文件
- 打開此文件
- 在此文件中注入並聲明 import {Injectable,BgModule} from '@angular/core'
- 聲明引入的組件模塊 @Injectable() @NgModule()
- 開始進行封裝
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)
}
}
- 在此文件夾中新建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文件中寫入
- 先引用注入
import TokenUtil from '../../utils/token.util'
-
import { AppRoutingModule } from './app-routing.module';
-
@Injectable()
-
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中聲明一次
- TokenUtil
- ReactiveFormsModule
- 在providers中進行一次(使用)
4.在對應的組件中ts中進行一次使用 服務引用