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

相关问题