0

I have HTML file from where I called my submit function from form tag,

<form [formGroup]="loginform" (ngSubmit)="loginUser(loginform)">

Yes, I have a complete form with all required field and submit button.

Next, in my angular file, my function is,

loginUser(form: FormGroup){
    let pass: DbModel = {
      reg_username: '',
      reg_email: '',
      reg_fullname: '',
      reg_dob: '',
      reg_gender: '',
      reg_password: ''
    };
    this.storageService.login(form).subscribe(data => pass = data);
    if(form.value.reg_password === pass.reg_password)
      console.log("Logged In...");
    else
      console.log("Wrong Credentials...");   }

Then, my service file is,

login(form: FormGroup): Observable<DbModel>{
return this.http.get<DbModel>('http://localhost:53685/api/users/'+form.value.reg_username);

}

Now, this API call is returning correct value but not at right time. When I debugged, I got expected return value of pass.reg_password to remain undefined, but as soon as I hit continue button in the debugger, the event completes and pass.reg_password has correct expected value.

How to resolve in angular 6, I am using HttpClientModule,Net WebAPI, SQL Database, And also I debugged my web api, it is returning the correct value.

When I checked network tab in chrome developer tools, it showed pending while debugging but ok 200 when the event ends.

Vikas
  • 11,859
  • 7
  • 45
  • 69
Abhishek Jaiswal
  • 243
  • 1
  • 18

1 Answers1

3

your validation is executed before your subscription is resolved you should do the form value check within the subscribe callback.

this.storageService.login(form).subscribe(data => {
    if(form.value.reg_password === data.reg_password)
      console.log("Logged In...");
    else
      console.log("Wrong Credentials...");
});

The catch is in this line:

return this.http.get<DbModel>'http://localhost:53685/api/users/'+form.value.reg_username);

http.get(...) is asynchronous an as such you need to deal with the response inside the subscribe() callback.

Vikas
  • 11,859
  • 7
  • 45
  • 69
Taranjit Kang
  • 2,510
  • 3
  • 20
  • 40
  • Yes sir, It solved my problem.But only for my curiosity, i learned that there used to be a resolve() for such problem. Can it still be used somehow, so that i can send the received data to someplace else, instead of just comparing in my if block. – Abhishek Jaiswal Jun 22 '18 at 19:12
  • by Invoking the method inside `subscribe` callback `.subscribe(value=>this.myMethod(value))` – Vikas Jun 22 '18 at 19:18
  • `resolve()` method works with `promises` it's recommended to use `observables` over `promises` Have a Look at [this](https://stackoverflow.com/questions/37364973/promise-vs-observable) – Vikas Jun 22 '18 at 19:25