2

I want to make the authorization header not to declare it again and again when i get something from the api.

I need to attached authorization headers every time i need to get data from the api. I am currently using HTTPCLIENT in Angular 4. My code:

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');           
            }

        });
    }
  }
}
1

1 Answer 1

6

Angular's HttpClient allows defining global interceptors.

You can define a simple interceptor which does nothing like this:

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

List it in the providers of an Angular module (you probably want AppModule), as the following.

{
  provide: HTTP_INTERCEPTORS,
  useClass: NoopInterceptor,
  multi: true,
}

All your requests will now pass through this interceptor.

For more information, read about 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);
  }
}

All code is copied from the docs.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks. But can you help me what should i do in my auth.service.ts. Can you edit it?
Lazar's answer is perfect, please accept it. In your auth.service.ts you need to provide a getAuthorizationHeader() method.
If you run into a circular dependency issue because AuthService depends on HttpClient which the AuthInterceptor modifies, then use another AuthHeaderService for managing the authorization header which you inject into both AuthService and AuthInterceptor to keep them uncoupled. The AuthService then sets the header using AuthHeaderService, and the AuthInterceptor gets the header using the AuthHeaderService.
Hey @Joseph -- it's been a year now. If this answer has solved your troubles, it'd be great if you could accept it so it's more clear to other visitors that it does solve the question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.