3

Currently I am facing issue regarding login authentication in angular js 2. In that I am facing the issue regarding asynchronous in following code.

   import { Injectable } from '@angular/core';

   import { Http } from '@angular/http';
   import { UserData } from './UserData';
   import 'rxjs/add/operator/map'
   import 'rxjs/add/operator/toPromise'

   @Injectable()
   export class LoginserviceService {

   userData = new UserData('','');

   constructor(private http:Http) { }

  callService(username:string,passwrod:string):boolean {
    var flag : boolean;      
   (this.http.get('http://localhost:4200/data.json').
   map(response => response.json())).subscribe(
     data => this.userData = data ,
     error => alert(),
     () => {
       flag = this.loginAuthentication(username,passwrod);
    }           
  );     
  return flag;
 }

loginAuthentication(username:string,passwrod:string):boolean{
 if(username==this.userData.username && passwrod==this.userData.password){
   return true;
 }else{
   return false;
 }
 }

When I am executing this code after passing currect username and password it is still return false.

return flag

is executing before

 flag = this.loginAuthentication(username,passwrod);

and finally I am getting result as false.

Is there any solution that If I can use synchronize method or promise in angular 2.

Below is component code

import { Component, OnInit } from '@angular/core';
import { LoginserviceService } from '../loginservice.service';

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

constructor(private service : LoginserviceService) { 

 }

 ngOnInit() {

 }
 save() {

 var flag =  this.service.callService(this.model.userName,this.model.passWord);
  if(flag==true)
   {
    console.log("login Successfully done-----------------------------")
    this.model.success = "Login Successfully done";
   }

}

}  
4
  • Can you please clarify where is each function called? Can you add your component code? Commented Oct 22, 2016 at 15:22
  • I updated the code..Please go through it .. Thanks Commented Oct 22, 2016 at 15:30
  • @stackinfostack can you debug your loginAuthentication method and see what data values are coming there. Commented Oct 22, 2016 at 15:51
  • I have also put console.log inside the first if condition.. That log is also printing(It means it is successully authenticated) .. but the things is that before executing loginAuthentication method callService method return flag (And by defult flag value is false)... Commented Oct 22, 2016 at 15:55

2 Answers 2

2

I think you got it right in your question - it's a synch/asynch issue. The http calls you are making are asynch by nature, and I think this is how you should handle them.

I would suggest that you return an observable in your service and handle the response in your component class - here's your code with minimal adjustments fromt he service class:

callService(username:string,passwrod:string):Observable<boolean> {
    var flag : boolean;      
    return (this.http.get('http://localhost:4200/data.json').
    map(response => response.json())).
    map(data => {
        this.userData = data;
        return this.loginAuthentication(username,passwrod);
    });
}

Then in your component class you can now call the save method like this:

save() {
    this.service.callService(this.model.userName,this.model.passWord).
    subscribe(
        success => {
            if(success) {
                console.log("login Successfully done-----------------------------");
                this.model.success = "Login Successfully done";
            },
        error => console.log("login did not work!")
    );
}

This should now work. I did not test the code, so it might not run out of the box, but I hope the point is clear.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your comment. This code is working perfectly with no error. Thank you so much .. I will put this again in answer with proper files.
1

Please find detail the answer as given by esef Below is component and service file.And Code is Working fine.

import { Component, OnInit } from '@angular/core';
import { LoginserviceService } from '../loginservice.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  model:any={};
  constructor(private service : LoginserviceService) { 
}

ngOnInit() {

}
save() {
   this.service.callService(this.model.userName,this.model.passWord).
   subscribe(
      success => {
        if(success) {
            console.log("login Successfully done----------------------------    -");
            this.model.success = "Login Successfully done";
     }},
    error => console.log("login did not work!")
  );
 }

}

Below is service file..

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { UserData } from './UserData';
import 'rxjs/add/operator/map'
import 'rxjs/add/operator/toPromise'
import {Observable} from 'rxjs/Rx'

@Injectable()
   export class LoginserviceService {
   userData = new UserData('','');   
   constructor(private http:Http) { }

    callService(username:string,passwrod:string):Observable<boolean> {
     var flag : boolean;      
     return (this.http.get('http://localhost:4200/data.json').
       map(response => response.json())).
        map(data => {
          this.userData = data;
          return this.loginAuthentication(username,passwrod);
        });
      }

  loginAuthentication(username:string,passwrod:string):boolean{
     if(username==this.userData.username && passwrod==this.userData.password){
        console.log("Authentication successfully")
        return true;
   }else{
     return false;
   }


  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.