How to return value from function processing observable of RXJS in Angular

637 views Asked by At

I have a login view in Angular. I have made:

  1. an UserService to fetch User Data.

  2. an AuthService for checking valid User.

So from login view, I pass the username to AuthService and it contacts with UserService for the data and manipulates data and return a boolean value whether the user is valid or not.

code goes below from login view is as follows:

AuthenticationService:

this.authenticationService.checkValidLogin(userName,password);

AuthenticationService:

checkValidLogin(username: string, password: string) {
    this.userService.getUserByEmail(username).snapshotChanges().pipe(map(data => data.map(c => ({ key: c.payload.doc.id, ...c.payload.doc.data() })))).subscribe(res => {
        if (res[0].password === password) {
            return true;
        } else {
            return false;
        }
    });
}

I have return true or false but that wont return to the method..!!

I want to return true or false value from subscription or what I am missing here?

2

There are 2 answers

1
AliF50 On BEST ANSWER

Since the code is asynchronous, you have to return the Observable and subscribe to it when you want to check its validity.

checkValidLogin(username: string, password: string): Observable<boolean> {
    return this.userService.getUserByEmail(username).snapshotChanges().pipe(map(data => data.map(c => ({ key: c.payload.doc.id, ...c.payload.doc.data() }))),
// map result to true or false
map(res => {
      if (res[0].password === password) {
        return true;
      } else {
        return false;
      }
    })
);

Then when you want to use it:

this.authenticationService.checkValidLogin(userName,password).subscribe(valid => {
  console.log(valid); // do your logic here of everything that determines if it's valid or not
});
2
adhs91 On

Kindly add return before this.userService.getUserByEmail as below.

checkValidLogin(username: string, password: string){
return this.userService.getUserByEmail(username).snapshotChanges().pipe(map(data => data.map(c => ({ key: c.payload.doc.id, ...c.payload.doc.data() })))).subscribe(res => {
  if (res[0].password === password) {
    return true;
  } else {
    return false;
  }
});

I would also suggest to just return res[0].password === password as it returns a boolean value