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

相关内容

热门资讯

9分钟了解“WePoKer开挂... 9分钟了解“WePoKer开挂功能透视教程”开挂辅助安装(透视)技巧教程是一款可以让一直输的玩家,快...
开挂辅助安装"智星菠... 开挂辅助安装"智星菠萝辅助"开挂(透视)辅助神器(有挂秘诀)智星菠萝辅助ai黑科技系统规律教程开挂技...
推荐十款“wepoker免费透... 无需打开直接搜索加微信客服(136704302)咨询了解wepoker免费透视脚本辅助器目前(微信:...
开挂辅助神器"wpk... 开挂辅助神器"wpk透视辅助"开挂(透视)辅助插件(真是有挂)《详细加薇136704302咨询》游戏...
玩家必看攻略“wepoker辅... 无需打开直接搜索加微信客服(136704302)咨询了解wepoker辅助开挂辅助器目前(微信:13...
开挂辅助工具"拱趴大... 【亲,拱趴大菠萝万能辅助器 这款游戏可以开挂的,确实是有挂的,很多玩家在这款拱趴大菠萝万能辅助器中打...
推荐一款“微扑克辅助器免费版”... 您好:微扑克辅助器免费版这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用户的...
开挂辅助安装"德普软... 【亲,德普软件 这款游戏可以开挂的,确实是有挂的,很多玩家在这款德普软件中打牌都会发现很多用户的牌特...
科技通报“wepokerplu... wepokerplus辅助透视教程是一款可以让一直输的玩家,快速成为一个“必胜”的ai辅助神器,有需...
开挂辅助安装"we ... 开挂辅助安装"we poker免费辅助器"开挂(透视)辅助插件(有挂规律) >>您好:软件加薇136...