我希望授权标题不会在我从api获取内容时一次又一次地声明它。
每次需要从api获取数据时,我都需要附加授权标头。我目前在Angular 4中使用HTTPCLIENT。我的代码:
auth.service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import 'rxjs/add/operator/map';
import { AppSettings } from '../app.constants';
@Injectable()
export class AuthService {
private loggedIn = false;
constructor(private httpClient: HttpClient) {
}
loginUser(email: string, password: string) {
const headers = new HttpHeaders()
.set('Content-Type', 'application/json');
return this.httpClient
.post(
GLOBAL_URL.LOGIN_URL + '/auth/login',
JSON.stringify({ email, password }),
{ headers: headers }
)
.map(
(response: any) => {
localStorage.setItem('auth_token', response.token);
this.loggedIn = true;
return response;
});
}
isLoggedIn() {
if (localStorage.getItem('auth_token')) {
return this.loggedIn = true;
}
}
logout() {
localStorage.removeItem('auth_token');
this.loggedIn = false;
}
products.service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders} from '@angular/common/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/of';
import{ GloablSettings } from '../global.constants';
@Injectable()
export class SettingsService {
settingslist: any;
settings: any;
constructor(private httpClient: HttpClient) {}
getSettings(){
if(this.settingslist != null) {
return Observable.of(this.settingslist);
}
else {
const authToken = localStorage.getItem('auth_token');
const headers = new HttpHeaders()
.set('Content-Type', 'application/json')
.set('Authorization', `Bearer ${authToken}`);
return this.httpClient
.get(GLOBAL_URL.GET_URL + '/settings/product', { headers: headers })
.map((response => response))
.do(settingslist => this.settingslist = settingslist)
.catch(e => {
if (e.status === 401) {
return Observable.throw('Unauthorized');
}
});
}
}
}
答案 0 :(得分:5)
Angular' HttpClient
允许定义全局拦截器。
你可以定义一个简单的拦截器,它不会做这样的事情:
@Injectable()
export class NoopInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req);
}
}
在Angular模块的提供程序中列出它(您可能需要AppModule
),如下所示。
{
provide: HTTP_INTERCEPTORS,
useClass: NoopInterceptor,
multi: true,
}
您的所有请求现在都将通过此拦截器。
有关详细信息,请参阅官方指南中的HttpClient
interceptors in Angular。在那里,您可以找到所需的确切用例:setting headers on every request。
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private auth: AuthService) {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// Get the auth header from the service.
const authHeader = this.auth.getAuthorizationHeader();
// Clone the request to add the new header.
const authReq = req.clone({headers: req.headers.set('Authorization', authHeader)});
// Pass on the cloned request instead of the original request.
return next.handle(authReq);
}
}
所有代码都是从文档中复制的。