我的拦截器服务是将授权头添加到我的http调用中,但是未能包含我传递给拦截器服务的实际承载令牌值。 chrome dev工具中显示的bearer token值只是'not set'值,而不是bearer token值。当我从登录组件控制台登录时,承载令牌值确实正确显示,因此我知道它是否已设置,但我想它会在之后的http中使用之前重置为“未设置”值。呼叫?
import { Component, OnInit } from '@angular/core';
import { Router } from "@angular/router";
import { HttpClient } from "@angular/common/http";
import { Response, Headers, RequestOptions } from "@angular/http";
import { AuthInterceptor } from "../../services/authInterceptor.service";
import { MatSnackBar } from '@angular/material';
import "rxjs/Rx";
@Component({
selector: 'login',
templateUrl: './login.component.html'
})
export class LoginComponent implements OnInit {
memberLogin: any = {
'emailAddress': '',
'password': ''
};
public constructor(private http: HttpClient, private authInterceptor: AuthInterceptor, public snackBar: MatSnackBar, public router: Router) {
}
public ngOnInit() {
}
public login() {
let url: string = 'http://localhost:63741/api/Account/Login';
let body = { "Email": this.memberLogin.emailAddress, "Password": this.memberLogin.password };
this.http.post(url, body)
.subscribe(
data => {
this.authInterceptor.authToken = data.toString();
console.log('token data in login component : ' + this.authInterceptor.authToken);
this.snackBar.open('welcome back, you are now logged in', 'ok', { duration: 2200 })
},
err => {
});
return;
};
}
import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class AuthInterceptor {
authToken: string = 'not set';
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const authReq = req.clone({ headers: req.headers.set('Authorization', 'Bearer ' + this.authToken ) });
return next.handle(authReq);
}
}
答案 0 :(得分:1)
您注入LoginComponent的AuthInterceptor与HttpClient框架使用的对象(即AppModule中HTTP_INTERCEPTORS的useClass中的对象)不同。
让AuthInterceptor使用一个新的注射器,比如说AuthService,你可以在其中存储authToken。将它注入AuthInterceptor和LoginComponent:
@Injectable()
export class AuthService {
public authToken: string = 'not set';
}
确保在AppModule中将其声明为提供程序。