我想讓授權頭不要一次又一次地聲明它,當我從API獲取某些東西時。爲角度4中的每個Http請求製作全局身份驗證頭
我需要附加授權標題每次我需要從API獲取數據。我目前正在使用的HttpClient在角4.我的代碼:
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');
}
});
}
}
}
看看httpclient攔截器https://alligator.io/angular/httpclient-interceptors/ – Whisher