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

相关内容

热门资讯

玩家实测“九游辅助器”开挂(透... 九游辅助器 无需打开直接搜索微信:136704302本司针对手游进行,选择我们的四大理由: 1、软件...
最新技巧“sohoo开挂辅助”... sohoo开挂辅助是一款专注玩家量身打造的游戏记牌类型软件,在sohoo开挂辅助这款游戏中我们可以记...
分享一款“盛世辅助”开挂(透视... 大家好,今天小编来为大家解答盛世辅助这个问题咨询软件客服可以免费测试直接加微信(136704302)...
透视软件“闽游十三水辅助”开挂... 透视软件“闽游十三水辅助”开挂(透视)辅助脚本揭秘攻略(有挂技术) 【无需打开直接搜索加薇13670...
专业讨论“开心十三张脚本”开挂... 专业讨论“开心十三张脚本”开挂(透视)辅助插件必备教程(有挂细节)《详细加薇136704302咨询》...
查到实测“悠悠互娱辅助”开挂(... 查到实测“悠悠互娱辅助”开挂(透视)辅助安装爆料教程(果真有挂)这是一款可以让一直输的玩家,快速成为...
揭秘真相“蜜瓜大厅小程序辅助”... 您好:这款蜜瓜大厅小程序辅助游戏是可以开挂的,确实是有挂的,很多玩家在这款蜜瓜大厅小程序辅助游戏中打...
透视实锤“雀神广东麻将透视视频... 透视实锤“雀神广东麻将透视视频”开挂(透视)辅助平台透明挂教程(有挂猫腻) 【无需打开直接搜索加薇1...
分享实测“吉祥填大坑脚本”开挂... 分享实测“吉祥填大坑脚本”开挂(透视)辅助透视普及教程(新版有挂)>>您好:软件加薇13670430...
重大推荐“传送屋app辅助脚本... 重大推荐“传送屋app辅助脚本下载”开挂(透视)辅助软件可靠技巧(详细教程)传送屋app辅助脚本下载...