moh
moh

Reputation: 443

set JWT token in header in angular 5 app

hi im working on django rest framwork for backend and angular 5 app as client .. i need to send JWT token and Content-Type in each request to server how can i set "jsonwebtoken" and "content-type" in request header???? looks like RequestOptions and Header are deprecated in angular 5 any solution???

import {Injectable} from '@angular/core';
import {Headers, RequestOptions} from '@angular/http'
import {HttpClient} from "@angular/common/http";
import 'rxjs/add/operator/map'


@Injectable()
export class UserService {

  private options;
  constructor(private http: HttpClient) {
    const token = localStorage.getItem('theuser');

    const headers = new Headers();
    headers.append('Content-Type', 'application/json');
    headers.append('Authorization', 'Bearer' + ' ' + token)
    this.options = new RequestOptions({headers: headers});

    console.log(this.options)
  }


  userInfo() {
    return this.http.get<any>("http://localhost:8000/user-detail/",this.options)

  }

}

Upvotes: 0

Views: 2014

Answers (2)

Tushar Nikam
Tushar Nikam

Reputation: 624

You can extend the http interceptor class. Create new service token.interceptor.ts with following content.

import { Injectable } from '@angular/core';

import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor
} from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
declare var localStorage : any;

@Injectable()
export class TokenInterceptor implements HttpInterceptor {
  constructor() {}
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    let allowedUrls =( request.url.indexOf("dealer/signup") < 0 && request.url.indexOf("dealer/login") < 0 );   

    if(allowedUrls){

        let authToken = localStorage.getItem("dealertoken");
        request = request.clone({
            headers: request.headers.set('Authorization', 'Bearer '+ authToken)
            /* setHeaders: {
                Authorization: 'Bearer '+ authToken
            } */
        });
    }
    return next.handle(request);
  }
}

and import it in app.module.ts

providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: TokenInterceptor,
      multi: true
    }
  ],

Upvotes: 1

Suren Srapyan
Suren Srapyan

Reputation: 68685

The second parameter which you have passed is the options. It contains headers property. You can add the headers into this property.

What about deprecated - import HttpHeaders from the @angular/common/http.

If you need to add the JWT for each token, it will be better to use HttpInterceptor

Upvotes: 0

Related Questions