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

相关内容

热门资讯

透视ai"欢乐茶馆脚... 透视ai"欢乐茶馆脚本辅助"开挂(透视)wejoker手机版透视脚本(有挂教学);1、超多福利:超高...
推荐几款新版"aap... 推荐几款新版"aapoker透视脚本"开挂(透视)wpk私人局辅助是真的吗(真是有挂);一、有挂的是...
详细说明"微乐贵阳捉... 详细说明"微乐贵阳捉鸡麻将辅助"开挂(透视)poker world辅助(有挂教学);1.微乐贵阳捉鸡...
研究成果"都莱辅助器... 研究成果"都莱辅助器"开挂(透视)wejoker辅助软件价格(有挂技巧);1、让任何用户在无需AI插...
专业讨论"大唐山西辅... 专业讨论"大唐山西辅助"开挂(透视)hhpoker破解工具(今日头条);软件透视开挂更新新赛季,主要...
重要通知"赤峰对调同... 【福星临门,好运相随】;重要通知"赤峰对调同城游辅助"开挂(透视)wepoker亲友圈有用吗(有挂总...
揭秘攻略"手机填大坑... 揭秘攻略"手机填大坑辅助器"开挂(透视)hhpoker有没有外挂(有挂工具);1、很好的手机填大坑辅...
技术分享"西兵辅助器... 技术分享"西兵辅助器"开挂(透视)wepoker有没有机器人(有挂秘笈);详细西兵辅助器攻略(西兵辅...
一分钟了解"心悦透视... 一分钟了解"心悦透视辅助软件"开挂(透视)aapoker透视插件(有挂秘籍),是用手机号来登录游戏的...
玩家攻略推荐"老夫子... 玩家攻略推荐"老夫子拼十辅助"开挂(透视)wpk模拟器(有挂教学);超受欢迎的稳赢小游戏,经典的ai...