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";
}
}
}
loginAuthenticationmethod and see what data values are coming there.