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
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; } }
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(); } }
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