0

I'm having authService that calls my backend endpoint to authenticate and I want to simply return true/false to another component so I can display/hide error message. On top of that, on success I want to store token in localStorage.

signIn = (signInFormValue) => {
    var response = this.authService.authenticate(signInFormValue.username, signInFormValue.password)
      if(response) {      
        console.log(response)
        this.invalidCredentials = false;
      } else {
        this.invalidCredentials = true;
      }      
  }

Which calls this

authenticate(username: string, password: string) {
    return this.callAuthenticationEndpoint(username, password).pipe(map(res =>{
      localStorage.setItem('token', res.headers.get('Authorization');
      return true;
    }, err => {return false}))
  }

  callAuthenticationEndpoint(username: string, password: string): Observable<any> {
    var url = this.AUTHENTICATE_URL + 'username=' + username + '&password=' + password;
    return this.http.get(url, {observe: "response"});
  }

The problem is, response isn't true/false, but it is

enter image description here

Weeedooo
  • 501
  • 8
  • 25
  • Should use the subscribe method with the first call to your service with the component have injected the HttpClient to use the service.. then that response will be true or false.. also by default the method return an observable, should use typescript over the authenticate method like.. authenticate(username: string, password: string) : Boolean – Joel Garcia Nuño Aug 15 '19 at 09:55

1 Answers1

1

What you receive from the service is an Observable. To get the boolean response you want, you have to subscribe to this Observable:

signIn(signInFormValue){
 return this.authService
        .authenticate(signInFormValue.username, signInFormValue.password)
        .subscribe(response => console.log(response));
}
Matt Walterspieler
  • 2,073
  • 2
  • 21
  • 34