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

相关内容

热门资讯

透视工具!微乐家乡app插件,... 透视工具!微乐家乡app插件,新悠悠辅助(透视)开挂辅助神器可靠教程1、下载安装好微乐家乡app插件...
素来有辅助"广西老友... 素来有辅助"广西老友玩友破解视频"详细开挂辅助神器有挂分享(解密教程);无需打开直接搜索打开薇:13...
固有有开挂"中至辅助... 中至辅助器开挂教程视频分享装挂详细步骤在当今的网络游戏中,中至辅助器作为一种经典的娱乐方式,吸引了无...
方案开挂"情怀至友开... 方案开挂"情怀至友开挂"开挂(软件)辅助安装(有挂技术);无需打开直接搜索打开薇:136704302...
透视ai!微信小程序辅助多少钱... 透视ai!微信小程序辅助多少钱,玄龙大厅怎么开辅助(透视)开挂辅助下载玩家教你 了解更多开挂安装加(...
一向有辅助"椰岛常胜... 一向有辅助"椰岛常胜游戏挂机"详细开挂辅助平台有挂存在(插件教程)>>您好:软件加薇13670430...
原先有辅助"小程序牵... 小程序牵手跑得快辅助器是一款专注玩家量身打造的游戏记牌类型软件,在小程序牵手跑得快辅助器这款游戏中我...
法子辅助"广丰510... 法子辅助"广丰510k同城游攻略"开挂(透视)辅助神器(有挂神器)广丰510k同城游攻略ai黑科技系...
透视存在!大唐山西辅助,微乐家... 透视存在!大唐山西辅助,微乐家乡游戏攻略(透视)开挂辅助安装揭秘教程;亲,微乐家乡游戏攻略这款游戏原...
最初有开挂"功夫川麻... 较多好评“微乐万能挂官网”开挂(透视)辅助教程 了解更多开挂安装加(136704302)微信号是一款...