为 Angular 中的每个 Http 请求进行全局身份验证 Header 4

Making Global Authentication Header For Every Http Request in Angular 4

我想授权 header 当我从 api 那里得到东西时,不要一次又一次地声明它。

每次我需要从 api 获取数据时,我都需要附加授权 header。我目前在 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');           
            }

        });
    }
  }
}

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 in the official guide. There you can find the exact use-case which you want: 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);
  }
}

所有代码均复制自文档。