0

This is the Auth Service file in which I have assigned the token value to the global this.token variable, but I am not able to get the value of this.token outside the subscribe. As I am a newbie in this, please point out the mistakes I have done for this. Your answers would be very appreciated!

import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http';
import { Router } from '@angular/router';
import { User } from './user.model';

@Injectable({providedIn: 'root'})
export class AuthService {

  private token: string;

  constructor(
    private httpClient: HttpClient,
    private router: Router
  ){
  }

  getToken() {
    return this.token;
  }

  signup(username: string, email: string, password: string) {
    const user: User = {
      username: username,
      email: email,
      password: password
    }

    this.httpClient.post<{success: boolean, message: string}>('http://localhost:3000/signup', user)
    .subscribe((responseData) => {
      if(!responseData.success){
        console.log(responseData.message)
      }
      else{
        console.log(responseData.message)
      }
    })
  }

  login(email: string, password: string){
    const user: User= {
      username: null,
      email: email,
      password: password
    }

    this.httpClient.post<{token: string}>('http://localhost:3000/login', user)
    .subscribe((responseData) => {

      const auth_token = responseData.token;
      this.token = auth_token;
      console.log(this.token)
    })
  }

}
Abhinab Roy
  • 1
  • 1
  • 2
  • It's not a global, it's just a property. You haven't shown when/how you're *calling* `getToken`, but the problem is that you're doing that too soon. See the linked questions' answers for why. – T.J. Crowder Mar 16 '21 at 12:16
  • Sorry @T.J.Crowder but I cannot understand, what wrong I am doing here. I am a newbie in this. The this.token value remains undefined outside the subscribe. Can you please point out the mistake, so that I can learn. Thank you. – Abhinab Roy Mar 16 '21 at 14:21

0 Answers0