0

我想讓授權頭不要一次又一次地聲明它,當我從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');   
      } 

     }); 
    } 
    } 
} 
+0

看看httpclient攔截器https://alligator.io/angular/httpclient-interceptors/ – Whisher

回答

-2

可以爲自己的http客戶端包裝HttpClient

4

Angular的HttpClinet允許定義全局攔截器。

您可以定義一個簡單的攔截它什麼也不做這樣的:

@Injectable() 
export class NoopInterceptor implements HttpInterceptor { 
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { 
    return next.handle(req); 
    } 
} 

在角度模塊的供應商名單(您可能想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); 
    } 
} 

所有代碼被從文檔複製。

+0

謝謝。但是,你能幫我在auth.service.ts中做什麼。你可以編輯它嗎? – Joseph

+0

拉扎爾的答案是完美的,請接受它。在你的auth.service.ts中,你需要提供一個getAuthorizationHeader()方法。 – Cito

+0

如果您遇到循環依賴性問題,因爲AuthService依賴於AuthInterceptor修改的HttpClient,然後使用另一個AuthHeaderService來管理您注入到AuthService和AuthInterceptor中的授權頭,以使它們解除耦合。然後AuthService使用AuthHeaderService設置標題,AuthInterceptor使用AuthHeaderService獲取標題。 – Cito

相關問題