0

My Service

import { Injectable } from '@angular/core';
import {Observable} from 'rxjs';
import { HttpClient,HttpParams } from '@angular/common/http';

@Injectable()
export class UserService {

  constructor(private http: HttpClient) { }
  isAdmin;
  getLogIn(email:string,password:string):Observable<boolean>{
    let params = new HttpParams().set("userEmail",email).set("userPassword", password);
    return this.http.get<boolean>("http://localhost:8080/user/login",{params: params});
     }
}

My Subscribe call

 email:string="";
  password:string="";
  adminFlag:boolean=false;

  login(event: any) {
    console.log(this.adminFlag);
    this.userService.getLogIn(this.email,this.password).subscribe(data => this.adminFlag=(data));
    console.log(this.adminFlag);
    if(this.adminFlag){
      console.log("INSIDE IF")
        this.router.navigate("../../home");
    }
  }

When i log in data var in console I am getting raw data as

true

but i couldn't assign it to this boolean "adminFlag" it is changed to undefined

Anything I missed...???

the API is returning a boolean..I need that boolean to be assigned...

  • Where have you checked that the response is a boolean? In the service? Also, you should have the adminFlag checks inside the subscribe. Is this just a typo? – Kurt Hamilton Feb 16 '20 at 19:25

2 Answers2

2

HTTP GET is an asynchronous request. Which means you are reading the variable adminFlag before it is being set. Move the routing inside callback to set the value and use it. Its also always good practice to include error callback in HTTP requests. This should work:

login(event: any) {
  this.userService.getLogIn(this.email,this.password).subscribe(
    data => {
      this.adminFlag = data; 
      if (data) {
        this.router.navigate("../../home");
      }
    },
    error => {
      console.error('getLogIn failed');
      // handle error...
    }
  );
}
ruth
  • 29,535
  • 4
  • 30
  • 57
0

When you are executing:

    this.userService.getLogIn(this.email,this.password).subscribe(data => this.adminFlag=(data));

it means that you expect DATA to be a boolean. It's an observable boolean instead. To get the real boolean, use the pipe function, eg:

getLogIn(email:string,password:string):boolean{
  let params = new HttpParams().set("userEmail",email).set("userPassword", password);
  return this.http
    .get<boolean>("http://localhost:8080/user/login",{params: params})
    .pipe(map(data => data);
}
Gaetano Piazzolla
  • 1,388
  • 1
  • 16
  • 31