0

I create a function that is responsible for logging in. it looks like: (authService code)

 login(username: string, password: string) {
  return new Promise((resolve, reject) => {
    this.checkUser(username, password).subscribe((output) => {
      if (output.token) {
        console.log('Log in true');
        resolve();
      } else {
       reject();
      }
    });
  });
 }
 private checkUser(username: string, password: string): Observable<any> {
   return this.http.post<any>('api/auth', {username, password});
 }

I wanted to use Promise with resolve and reject to handle success and failure event in the call 'login' function, but I don't know why never in "if" dosn't go to the "else" section. AND I do not know why onSubmitSucces and onSubmitFailure execute in same time...

(loginComponent code)

 onSubmit() {

    this.authService.login(this.username, this.password)
      .then(this.onSubmitSuccess(), this.onSubmitFailure());

  }

  private onSubmitSuccess(): any {
    console.log('Success');
  }

  private onSubmitFailure(): any {
    console.log('Failure');

  }
Stephan
  • 61
  • 1
  • 1
  • 4
  • 3
    You are executing `onSubmitSuccess` (and `onSubmitFailure`) immediately instead of *passing* those functions as the `then` arguments: remove the `()`. As to the first problem, you should debug and see the actual value of `output.token` so you can understand why it never goes to the `else` section. Without knowing its value we cannot say much about it than that it apparently is never a falsy value. – trincot May 20 '18 at 13:45
  • What's the value of output.token? Try to console.log it to see. Your code never reaches `else` because output.token is not falsey, that's it. – Anton Harniakou May 20 '18 at 13:47
  • `this.authService.login(this.username, this.password) .then(this.onSubmitSuccess, this.onSubmitFailure);` Hmm, so should it look like this?? – Stephan May 20 '18 at 13:49
  • See @trincot's comment above, it's the same problem as the linked question, just with `then` instead of the `setTimeout` used there. – T.J. Crowder May 20 '18 at 13:53

0 Answers0