stackinfostack
stackinfostack

Reputation: 726

Angular 2 Synchronize of Http Service

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";
   }

}

}  

Upvotes: 3

Views: 2563

Answers (2)

stackinfostack
stackinfostack

Reputation: 726

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;
   }


  }
}

Upvotes: 1

esefs
esefs

Reputation: 88

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.

Upvotes: 2

Related Questions