Abhishek Jaiswal
Abhishek Jaiswal

Reputation: 253

Angular 6 - Observable Subscription remains Unresolved till the Event ends

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.

Upvotes: 0

Views: 429

Answers (1)

Taranjit Kang
Taranjit Kang

Reputation: 2580

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.

Upvotes: 3

Related Questions