0
votes

I have written a authentication service to authenticate user name and password in a Login Page. The code below is the service.

public login(credentials) {
   if (credentials.username === null || credentials.password === null) {
      return Observable.throw("Please insert credentials");
   } else {

   let apiURL = 'http://localhost/timeclock/api/login?usercode=' + credentials.username +
   '&password=' + credentials.password ;

   return Observable.create(observer => {     
    this.http.get(apiURL).map(res => res.json()).subscribe(data => {        
    if (data.success === 'true')
    {
      this.currentUser.name  = data.data.user_name;
      this.currentUser.email = data.data.user_email;
      observer.next(true);
      observer.complete();
    } else {
        observer.next(false);
        observer.complete();
      }      
    });
  });
}
}

When the user name and password is submitted, the URL is correctly called with the right parameters.

The http call takes very long time to complete. Also, no response is returned.

It takes only two or three seconds to get the response when I call the URL with the same parameters in the browser.

Any idea on how to fix this?

1
have you tried setting headers. also you are not setting a catch for any errors - Suraj Rao
I'd recommend you to use a POST for a login, this way the password isn't clearly visible in the URL and you can still retrieve the returned value. Now, your problem. Can you check in the chrome developer tools if your GET request is actually sent and what the response is? - Ivar Reukers
Thanks for your comments. I found that the call takes long time when the api is called first time. It works fine in the subsequent calls. Regarding the null response, I found that I need to setup headers in the API response before response is sent. Now, I am receiving the values from the API. - arun kumar

1 Answers

0
votes

You don't need to create a new Observable you can refactor like this.

public login(credentials) : Observable<boolean> {
  if (credentials.username === null || credentials.password === null) {
    return Observable.throw("Please insert credentials");
  } else {

    let apiURL = 'http://localhost/timeclock/api/login?usercode=' + credentials.username +
      '&password=' + credentials.password ;

    return this.http.get(apiURL).map(res => res.json())
      .map(data => 
      {
        if(data.success){
          this.currentUser.name  = data.data.user_name;
          this.currentUser.email = data.data.user_email;
          return true;
        }else{
          return false;
        }
      });
  }
}