Search code examples
angularauthenticationangular-servicesangular-componentsauth-guard

Auth Service and Login Component not communicating


I'm using Angular 4 and trying to return a boolean from the Auth Service, but when I try to console.log the value, it returns undefined.

I'm trying to return the boolean value and make a if/else statement redirecting the logged user to the dashboard.

My code is as follows:

login.component.ts

import { ModuleWithProviders } from '@angular/core';
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { AuthService } from '../auth/auth.service';

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

  constructor(
    private auth: AuthService,
    private router: Router
  ) { }

  ngOnInit() {
  }

  onSubmit(formData) {
    if(formData.valid) {
      var req = this.auth.isLoggedIn(formData.value.email, formData.value.password);
      if (req == true){
        this.router.navigate([ '/dashboard' ]);
      } else {
        alert("Login wasn't successful");
      }
    }
  }

}

auth.service.ts

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { HttpClient } from '@angular/common/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/do';

@Injectable()
export class AuthService {
  private _Url = 'http://localhost:3000/api/login';

  constructor(private http: HttpClient) {}

  isLoggedIn(email, password) {
    var data = {
      email: email,
      password: password
    };

    var req = this.http.post(this._Url, data)
    .subscribe(
      res => {return res['success'];},
      err => {return err['error']['success'];}
    );

  }

}

Also, on Login Component I'm getting an error that "Operator '==' cannot be applied to types 'void' and 'boolean'.

But let's not focus on that, because even without the if/else condition I'm always returning undefined.


Solution

  • Your isLoggedIn() method isn't actually returning anything. The return you have in your .subscribe actually return the response to the method but the method is not returning this value outside. I would write it like this:

    isLoggedIn(email, password): Observable<any> {
        const data = {
          email: email,
          password: password
        };
        return this.http.post(this._Url, data);
      }
    

    then in your login.component.ts

    onSubmit(formData) {
        if (formData.valid) {
          this.auth.isLoggedIn(formData.value.email, formData.value.password).subscribe( res => {
            if (res) {
              this.router.navigate(['/dashboard']);
            } else {
              alert("Login wasn't successful");
            }
          });
        }
      }
    

    Things to keep in mind:

    • In Typescript var keyword in not used anymore. Use let instead, or const for variables that are never reassigned.
    • If you're using TSLint it will complain if you try to check for equality with double equal operator ==, try using triple instead ===. It will perform a type check and save you from a lot of troubles, trust me.