0

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?

1
  • Is the data that you receive from userService an array? I'm asking since you have invoked a map operation on it data.map(c => ({ key: c.payload.doc.id, ...c.payload.doc.data() }) Commented Oct 7, 2020 at 15:39

2 Answers 2

1

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
});
Sign up to request clarification or add additional context in comments.

1 Comment

I will check and let you know..!!
0

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

2 Comments

Thanks for the answer will check and let you know as its simplier solution will approve this if it works..!!
This won't work, in this case we are returning a Subscription for the method and inside of the Subscription we are returning true or false.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.