Search code examples
angularangular2-services

angular 2 subscribe to observable getting undefined


I have a service and a component in angular 2 application , I am getting response in service and able to log to console also but it is showing undefined in component. whats wrong I am doing here? Can anybody point out the mistake. Thanks in advance

Service:

    import { Injectable } from '@angular/core'
import { Http, Response,Headers } from '@angular/http'
import { Observable } from 'rxjs/Observable'
import "rxjs/add/operator/map"
import "rxjs/add/operator/catch"
import "rxjs/add/Observable/throw"

@Injectable()
export class LoginService {
    public logResult;
    private _url = "http://localhost:53798/api/Login?uname=abcd&pass=1"


    constructor(private _http: Http) { }

getEmployees(userID:string,passWord:string) : Observable<boolean>{

    return this._http.get(this._url).map((response: Response) => 
        {
           let logResult= response.json();
           logResult.forEach(re=>{

              if(re.LoginResult=="Success")
              {
                  console.log('Success');//this is being written to console
                  return<boolean> true;
              }
              else{
                  console.log('fail');
                  return<boolean> false;
              }
            })
    }).catch(this._errorHandler);


}
_errorHandler(error: Response) {
    console.log(error);
    return Observable.throw(error || "Server not Found")
}
}

Componet :

 ValidateLogin(){


  this._loginService.getEmployees(this.loginForm.value.UserId,this.loginForm.value.password)

  .subscribe(resLoginData => {
      console.log(resLoginData);//resLoginData is undefined
      if(resLoginData===true)
      { 
          console.log('Success');
          this.router.navigateByUrl('/Home');}
      else{
        console.log('Fail');
        this.router.navigateByUrl('/Login');
      }
        resLoginError => this.errorMsg = resLoginError})           
 }     
}

Solution

  • forEach block won't stop at the return statement.

    let logResult= response.json().data;
    let result = false;
    logResult.forEach(re=>{
    
        if(re.LoginResult=="Success")
        {
            // console.log('Success');//this is being written to console
            result = true;
        }
        else{
            // console.log('fail');
            result false;
        }
    });
    
    return result;     // return the true result out of forEach.
    

    Also you should change let logResult= response.json(); to let logResult= response.json().data; for methods of http will return data this way.