0

私はAPIから何かを得るときに承認ヘッダーを何度も何度も宣言しないようにします。すべてのHTTPリクエストに対してグローバル認証ヘッダーを角4で作成する

私はAPIからデータを取得する必要があるたびに認証ヘッダーを添付する必要があります。

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

することができます:私は現在角度4.私のコードでのHttpClientを使用しています独自のHTTPクライアント用にHttpClientをラップする

4

AngularのHttpClinetでは、グローバルインターセプタを定義できます。以下のように、(おそらくAppModuleをしたい)アンギュラモジュールのプロバイダで

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

リストに:

あなたはこのように何もしない、単純なインターセプタを定義することができます。

{ 
    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に依存するため、循環依存関係の問題が発生した場合は、AuthServiceとAuthInterceptorの両方に注入した認証ヘッダーを管理するために別のAuthHeaderServiceを使用して、次に、AuthServiceはAuthHeaderServiceを使用してヘッダーを設定し、AuthInterceptorはAuthHeaderServiceを使用してヘッダーを取得します。 – Cito

関連する問題