Search code examples
angularheaderangular7angular-httpclient

How to set up a variable for a token In http header


I have a rest call and have created a header in my service. The problem I am facing right now is that , after 60 minutes , my token expires and I have to manually change the token inside my code.

I am trying to design a text box, where the user is just typing in the fresh token, and by clicking on the button, the token assigned variable is invoked and displays the data from my API.

I have already created a text box and button, but I am not sure how I can bring my logic of assigning the variable to my authroization token. and assigning them to my button.

I looked for resources around internet. But they are bit complicated. I am new to this, and looking forward for a simple solution. thank you.

Here is what I have tried so far.

Authenticate.html

<p>Please enter a valid token</p>
<input  #tokens
  (keyup.enter)="addtoken(tokens.value)"
       (blur)="addtoken(tokens.value); tokens.value = ''">

<button (click)="addtoken(tokens.value)">Send Request</button>

<ul><li *ngFor="let token of tokens">{{token}}</li> </ul>

here is my service.ts

import { Injectable } from '@angular/core';
import {HttpClient, HttpHeaders} from "@angular/common/http";



const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'application/json',
    'Authorization': 'Bearer  bafhejfbewfwlejfwfwe'
  })
};

@Injectable({
  providedIn: 'root'
})


export class DataService {

  constructor(private http: HttpClient) { }

  getlocations() {
    return this.http.get(
      'url' , httpOptions)
  }

}

Solution

  • Just create a method( updateHeader(updatedHeader) ) in your Service to update the header and call it from your Component:

    import { Injectable } from '@angular/core';
    import { HttpClient, HttpHeaders } from "@angular/common/http";
    
    @Injectable({
      providedIn: 'root'
    })
    export class DataService {
    
      httpOptions = {
        headers: new HttpHeaders({
          'Content-Type':  'application/json',
          'Authorization': 'Bearer  bafhejfbewfwlejfwfwe'
        })
      };
    
      constructor(private http: HttpClient) { }
    
      updateHeader(updatedHeader) {
        this.httpOptions.headers = this.httpOptions.headers.set('Authorization', `Bearer ${updatedHeader}`);
        console.log(this.httpOptions.headers.get('Authorization'));
      }
    
      getlocations() {
        console.log(this.httpOptions.headers.get('Authorization'));
        return this.http.get('url' , this.httpOptions);
      }
    
    }
    

    And then you can call this method inside your Component:

    import { Component } from '@angular/core';
    import { DataService } from './data.service';
    
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: [ './app.component.css' ]
    })
    export class AppComponent  {
    
      tokens = [];
    
      constructor(private dataService: DataService) {}
    
      addtoken(value) {
        if (value) {
          this.tokens.push(value);
          this.dataService.updateHeader(value);
        }
      }
    }
    

    Here's a Working Sample StackBlitz for your ref.