Angular 在Restanglar中登录后如何设置令牌?
登录Restanglar后,如何在标头中设置身份验证令牌?这是我的登录代码和应用程序模块声明Angular 在Restanglar中登录后如何设置令牌?,angular,restangular,Angular,Restangular,登录Restanglar后,如何在标头中设置身份验证令牌?这是我的登录代码和应用程序模块声明 this.authService .authenticate(this.login) .then(res => { if (res.data) { localStorage.setItem("currentUser", JSON.stringify(res.data)); // Restangular.setD
this.authService
.authenticate(this.login)
.then(res => {
if (res.data) {
localStorage.setItem("currentUser", JSON.stringify(res.data));
// Restangular.setDefaultRequestParams({ authentication: res.data.token });
// set heder token here
this.router.navigate(["member/home"]);
} else {
console.log("not found");
}
})
.catch(err => {
console.log(err);
});
app.module.ts
您可以使用拦截器模式实现此目标: 首先,创建一个新服务:
import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class JwtInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
let currentUser = JSON.parse(localStorage.getItem('currentUser'));
if (currentUser && currentUser.token) {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${currentUser.token}`
}
});
}
return next.handle(request);
}
}
import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class JwtInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
let currentUser = JSON.parse(localStorage.getItem('currentUser'));
if (currentUser && currentUser.token) {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${currentUser.token}`
}
});
}
return next.handle(request);
}
}
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true },
]