Add AuthInterceptor
that will intercept all your http requests and add the token to its headers:
import { Injectable } from '@angular/core';
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const token = localStorage.token; // you probably want to store it in localStorage or something
if (!token) {
return next.handle(req);
}
const req1 = req.clone({
headers: req.headers.set('Authorization', `Bearer ${token}`),
});
return next.handle(req1);
}
}
Then register it in your AppModule
:
@NgModule({
declarations: [...],
imports: [...],
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true },
],
bootstrap: [ AppComponent ],
})
export class AppModule { }
More about interceptors:
https://angular.io/guide/http#intercepting-requests-and-responses
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…