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

相关内容

热门资讯

1.9分钟了解!德州圈脚本,h... 1、1.9分钟了解!德州圈脚本,hhpoker开挂教程,专业教程(有挂方法);详细教程。2、hhpo...
揭秘真相!哈糖大菠萝可以开挂吗... 揭秘真相!哈糖大菠萝可以开挂吗,约局吧app有挂吗,细节方法(有挂神器)1、不需要AI权限,帮助你快...
交流学习经验!德州局透视脚本免... 交流学习经验!德州局透视脚本免费版下载手机版,pokemmo免费脚本,技巧教程(有挂教程);建议优先...
科技揭秘!hhpoker辅助挂... 科技揭秘!hhpoker辅助挂下载,红龙poker作弊指令,详细教程(有挂攻略)1、许多玩家不知道红...
玩家爆料!约局吧能不能开挂,w... 玩家爆料!约局吧能不能开挂,wepoker透视脚本苹果版,存在挂教程(有挂技巧)是一款可以让一直输的...
必知教程!wepoker底牌透... 必知教程!wepoker底牌透视,wepoker俱乐部辅助,玩家教你(有挂攻略);实战中需综合运用上...
分享一款!德州局怎么透视,智星... 分享一款!德州局怎么透视,智星菠萝透视,wpk教程(有挂透视);大神普及一款德州ai内幕,确定了德州...
交流学习经验!wepoker数... 交流学习经验!wepoker数据分析,德普之星透视辅助软件激活码,扑克教程(有挂辅助)是一款可以让一...
大神推荐!红龙poker辅助器... 大神推荐!红龙poker辅助器免费观看,epoker有透视吗,切实教程(有挂技巧)科技教程也叫必备教...
记者爆料!德扑圈透视,wepo... 记者爆料!德扑圈透视,wepoker辅助脚本,第三方教程(有挂技巧)是一款可以让一直输的玩家,快速成...