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、透视科技!德普之星辅助功能如何打开,德州辅助工具到底怎么样,新2025版(一贯真的是有挂);详细...
透视透视挂!wpk有脚本吗,佛... 透视透视挂!wpk有脚本吗,佛手大菠萝辅助,曝光教程(真是真的是有挂)1、完成wpk有脚本吗的残局,...
透视教学!wepoker辅助工... 此外,数据分析德州(wepoker辅助工具)辅助神器app还具备辅助透视行为开挂功能,通过对客户we...
透视美元局!wepoker透视... 透视美元局!wepoker透视脚本苹果版,wpk辅助器,透明挂教程(往昔是有挂)是一款可以让一直输的...
透视攻略!wpk辅助器下载,h... 透视攻略!wpk辅助器下载,hhpoker是内部控制吗,存在挂教程(素来真的是有挂)科技教程也叫必备...
透视黑科技!wpk辅助器下载,... 此外,数据分析德州(wpk辅助器下载)辅助神器app还具备辅助透视行为开挂功能,通过对客户wpk辅助...
辅助透视!wpk透视辅助,xp... 1、辅助透视!wpk透视辅助,xpoker辅助器,曝光教程(其实存在有挂);详细教程。2、wpk透视...
透视好牌!wpk脚本下载,哈糖... 透视好牌!wpk脚本下载,哈糖大菠萝有挂吗5个常用方法,详细教程(起初有挂) 科技详细教程;Q群10...
透视规律!aapoker有脚本... 透视规律!aapoker有脚本吗,aapoker透视脚本,2025版教程(一向存在有挂);实战中需综...
透视脚本!wepoker透视脚... 透视脚本!wepoker透视脚本免费,sohoo poker辅助,揭秘教程(素来是真的有挂);支持2...