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

相关内容

热门资讯

4分钟了解!微信微乐辅助免费!... 4分钟了解!微信微乐辅助免费!总是是真的有辅助脚本(有挂头条)-哔哩哔哩1、微信微乐辅助免费辅助器安...
第四分钟了解!中至吉安小程序微... 第四分钟了解!中至吉安小程序微信小程序!其实真的有辅助方法(有挂详情)-哔哩哔哩暗藏猫腻,小编详细说...
2分钟了解!新道游科技透视免费... 2分钟了解!新道游科技透视免费版下载网页!真是一直总是有辅助脚本(有挂分享)-哔哩哔哩1、用户打开应...
第5分钟了解!陕麻圈智能辅助器... 第5分钟了解!陕麻圈智能辅助器免费下载!好像是真的有辅助方法(有挂分享)-哔哩哔哩该软件可以轻松地帮...
九分钟了解!微信边锋辅助工具!... 九分钟了解!微信边锋辅助工具!都是一直都是有辅助插件(确实有挂)-哔哩哔哩1、微信边锋辅助工具公共底...
十分钟了解!顺欣茶楼辅助软件!... 十分钟了解!顺欣茶楼辅助软件!本来一直总是有辅助教程(新版有挂)-哔哩哔哩1、让任何用户在无需顺欣茶...
第一分钟了解!皮皮透视辅助软件... 第一分钟了解!皮皮透视辅助软件工具!原来存在有辅助软件(有挂细节)-哔哩哔哩1)皮皮透视辅助软件工具...
3分钟了解!天酷游戏交易平台!... 3分钟了解!天酷游戏交易平台!其实是有辅助工具(有挂解惑)-哔哩哔哩1、不需要AI权限,帮助你快速的...
第五分钟了解!wepoker辅... 第五分钟了解!wepoker辅助软件价格!确实是有辅助攻略(有挂方式)-哔哩哔哩wepoker辅助软...
两分钟了解!赣牌圈科技!确实一... 两分钟了解!赣牌圈科技!确实一直总是有辅助攻略(揭秘有挂)-哔哩哔哩1、许多玩家不知道赣牌圈科技辅助...