Sam
Sam

Reputation: 3

How to send variable in component.ts to service.ts for authentication Angular

I am trying to get auth_token from backend and use it in service class. The LoginComponent successfully sends user credentials and receives auth_token (verified through console.log). But I do not know how to use auth_token variable from component into the service class to put it in HttpHeaders.

I have a basic login html. My login.component.ts looks like this:

import { LoginService } from './../../service/login.service';
import { Router } from '@angular/router';
import { Login } from './../../model/login';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  login: Login;

  constructor(private service: LoginService,
    private router: Router) { }

  ngOnInit(): void {
    this.login = new Login();
  }

  sendLoginCredentials(){
    this.service.authorizeUser(this.login)
    .subscribe((data)=>{
      this.login.auth_token = data.auth_token;
      console.log(this.login.auth_token);
      this.router.navigate(['/home']);
    })
  }

}

The page redirects to home and I get a auth_token back. I have verified this through Postman and console.log(). Now I need to use this auth_token in Angular HttpHeaders in a different service class. Here is my department.service.ts to request a list of departments:

import { Login } from './../model/login';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Department } from '../model/department';
import 'rxjs/add/operator/map';

const URL = 'http://127.0.0.1:8000/api/';

@Injectable({
  providedIn: 'root',
})
export class DepartmentService {
  login: Login = new Login();

  httpHeaders = new HttpHeaders({
    'content-type': 'application/json',
    // Authorization: 'token 856f5464e0508620d4cb90d546817e201419a70e',
    Authorization: 'token ' + this.login.auth_token,
  });

  constructor(private http: HttpClient) {}

  getAllDepartments(): Observable<Department[]> {
    return this.http
      .get(URL + 'department-list/', { headers: this.httpHeaders })
      .map((resp) => resp as Department[]);
  }
}

The app works if I use hard coded value (in comments) but it gives me "token undefined" in Request Headers. I am not too experienced in Angular so I am stuck here. Thank you!!

Upvotes: 0

Views: 403

Answers (2)

abolfazl_mehdi
abolfazl_mehdi

Reputation: 365

you need to interceptor 
by interceptor you can set token in httpHeader

for example:

import {Injectable} from '@angular/core'; import {HttpRequest, HttpHandler, HttpEvent, HttpInterceptor} from '@angular/common/http'; import {Observable} from 'rxjs'; import {AuthService} from '@core/authentication';

@Injectable() export class JwtInterceptor implements HttpInterceptor {

constructor(private authService: AuthService) {
}

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const token = this.authService.getToken() ;
    if (token !== '') {
        const authReq = request.clone({
            setHeaders: {
                Authorization: `Bearer ${token}`
            }
        });
        return next.handle(authReq);
    } else {
    return next.handle(request);
    }


} }

Upvotes: 0

Zakariya Pindhariya
Zakariya Pindhariya

Reputation: 66

You need to use session instead of class for storing "auth_token"

sessionStorage.setItem("AuthToken", JSON.stringify(data.auth_token));

and whenever you use just get from session and use it like:

let authValue = sessionStorage.getItem("AuthToken");

httpHeaders = new HttpHeaders({
    'content-type': 'application/json',
    Authorization: 'token ' + authValue,
});

Upvotes: 1

Related Questions