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

相关内容

热门资讯

开挂辅助脚本"黑侠破... 开挂辅助脚本"黑侠破解wepoker"开挂(透视)辅助平台(有挂助手);无需打开直接搜索打开薇:13...
开挂辅助安装"德普之... 开挂辅助安装"德普之星透视免费"开挂(透视)辅助平台(证实有挂);无需打开直接搜索薇:1367043...
开挂辅助工具"hhp... 大家好,今天小编来为大家解答hhpoker辅助实战视频这个问题咨询软件客服可以免费测试直接加微信(1...
开挂辅助脚本"拱趴游... 【亲,拱趴游戏破解器 这款游戏可以开挂的,确实是有挂的,很多玩家在这款拱趴游戏破解器中打牌都会发现很...
开挂辅助安装"hh ... 较多好评“微乐万能挂官网”开挂(透视)辅助教程 了解更多开挂安装加(136704302)微信号是一款...
开挂辅助脚本"hhp... 开挂辅助脚本"hhpoker可以控制牌吗"开挂(透视)辅助插件(有挂秘籍);无需打开直接搜索薇:13...
开挂辅助软件"pok... 开挂辅助软件"pokemmo手机版脚本免费"开挂(透视)辅助插件(有挂助手);无需打开直接搜索打开薇...
开挂辅助工具"约局吧... 您好:这款约局吧透视挂下载游戏是可以开挂的,确实是有挂的,很多玩家在这款约局吧透视挂下载游戏中打牌都...
开挂辅助脚本"pok... 开挂辅助脚本"pokerrrr2辅助"开挂(透视)辅助神器(有挂方法)1、下载安装好pokerrrr...
开挂辅助下载"aap... aapoker透视方法是一款可以让一直输的玩家,快速成为一个“必胜”的ai辅助神器,有需要的用户可以...