Angular如何在页面加载时使用生成的BearerToken?
创始人
2024-10-29 09:00:16
0
  1. 在你的应用程序中创建一个AuthService来处理所有的身份验证逻辑:

import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { BehaviorSubject } from 'rxjs'; import { tap } from 'rxjs/operators';

@Injectable({ providedIn: 'root' }) export class AuthService { private readonly tokenUrl = '/api/auth/token'; private readonly tokenKey = 'auth-token'; private authToken$ = new BehaviorSubject(null);

constructor(private http: HttpClient) { this.loadToken(); }

private loadToken() { const token = localStorage.getItem(this.tokenKey); this.authToken$.next(token); }

getAuthToken() { return this.authToken$.value; }

setAuthToken(token: string) { localStorage.setItem(this.tokenKey, token); this.authToken$.next(token); }

login(username: string, password: string) { return this.http.post(this.tokenUrl, { username, password }) .pipe( tap((data: { token: string }) => this.setAuthToken(data.token)) ); }

logout() { localStorage.removeItem(this.tokenKey); this.authToken$.next(null); }

isAuthenticated() { return !!this.authToken$.value; } }

  1. 在你的AppComponent中调用AuthService的login方法以获取Token:

import { Component } from '@angular/core'; import { AuthService } from './auth.service';

@Component({ selector: 'app-root', template: }) export class AppComponent { constructor(private authService: AuthService) {}

ngOnInit() { this.authService.login('your-username', 'your-password').subscribe(); } }

  1. 在Http请求时使用Bearer Token:

import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { AuthService } from './auth.service';

@Injectable({ providedIn: 'root' }) export class DataService { constructor(private http: HttpClient, private authService: AuthService) {}

getData() { const headers = new HttpHeaders().set('Authorization', Bearer ${this.authService.getAuthToken()}); return this.http.get('/api/data', { headers }); } }

这样做可以在页面加载时自动获取Token,并将其存储在localStorage中。在您的应用程序中的任何Http

相关内容

热门资讯

开挂辅助插件"wep... 较多好评“微乐万能挂官网”开挂(透视)辅助教程 了解更多开挂安装加(136704302)微信号是一款...
开挂辅助神器"wpk... 【亲,wpk德州局透视 这款游戏可以开挂的,确实是有挂的,很多玩家在这款wpk德州局透视中打牌都会发...
开挂辅助神器"wep... wepoker透视app下载开挂教程视频分享装挂详细步骤在当今的网络游戏中,wepoker透视app...
开挂辅助工具"hhp... 开挂辅助工具"hhpoker有没有辅助挂"开挂(透视)辅助下载(有挂解密);无需打开直接搜索加薇13...
开挂辅助平台"har... 【亲,hardrock辅助 这款游戏可以开挂的,确实是有挂的,很多玩家在这款hardrock辅助中打...
开挂辅助神器"拱趴大... 开挂辅助神器"拱趴大菠萝挂"开挂(透视)辅助插件(真的有挂)《详细加薇136704302咨询》游戏特...
开挂辅助神器"wep... 开挂辅助神器"wepoker私人局怎么玩"开挂(透视)辅助脚本(有人有挂);无需打开直接搜索加(薇:...
开挂辅助安装"wep... 开挂辅助安装"wepoker黑侠破解"开挂(透视)辅助工具(有挂猫腻)《详细加薇136704302咨...
开挂辅助平台"wpk... 开挂辅助平台"wpk有辅助吗"开挂(透视)辅助脚本(有挂实锤)>>您好:软件加136704302中薇...
开挂辅助软件"we-... 较多好评“微乐万能挂官网”开挂(透视)辅助教程 了解更多开挂安装加(136704302)微信号是一款...