Whenever I am calling the checkLoginData(email: string, password: string) method with some email and some password, the return statement is executed before the function call to getUsersAndCheck(email: string, password: string) is finished. This is a problem as my code depends on the function call to be finished in order to get a correct return statement. Here is my code:
import { Injectable } from '@angular/core';
//import { LOGINDATA } from '../mock-users'; // bad approach use mock back end
import { GetDbDataService} from '../get-db-data.service';
import { User } from '../user';
import { OnInit } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class CheckLoginDataService implements OnInit{
//loginData = LOGINDATA;
authentication: boolean = false;
users: User[];
constructor(private getDbDataService: GetDbDataService) { }
ngOnInit(){
this.getUsers();
this.getUsersAndCheck("", ""); // call with empty strings to make compiler happy
console.log("Initialized check-login-data.service");
}
getUsers(): void {
console.log("getUsers() called");
this.getDbDataService.getUsers()
.subscribe(users => {this.users = users;
this.logUsers();
console.log("getUsers() call finished");
});
}
logUsers(): void{
this.users.forEach( (User) =>{
console.log("id: " + User.id + " password: " + User.password);
})
}
getUsersAndCheck(email: string, password: string){
console.log("getUsers() called");
this.getDbDataService.getUsers()
.subscribe(users => {this.users = users;
this.checkUserData(email, password);
console.log("getUsers() call finished");
});
}
checkUserData(email: string, password: string){
this.authentication = false;
this.users.forEach( (User) =>{
if(email === User.id && password === User.password){
this.authentication = true;
console.log("got it! authentication valie: " + this.authentication);
}
})
}
checkLoginData(email: string, password: string){
this.getUsersAndCheck(email, password);
console.log("return authentication valie: " + this.authentication);
return this.authentication;
}
}
Why does this happen? And how can I fix it?
Thank you really much in advance, I would be so lost without this communities help... Best regards, Sam