I think I am misunderstanding Subscriptions and Observables and I am not finding the Angular documentation particularly helpful.
I am creating a validationService meant to check if a username is available. The validationService is called on form submit and will display an error message if the username is unavailable. The problem is, i have to submit the form twice for it to work.
The validationService makes a http call to the backend that returns a boolean. I have a local variable 'availableUsername' that I want to set the result to, so that I can use it elsewhere. Inside the subscribe function it works fine, I get the result and I set it to this variable. But when I leave the scope of the subscribe method, the variable is undefined. But when I call submit again, it works.
I have added the validationService and userService below.
validationService.ts
import { Injectable } from '@angular/core';
import { FormControl } from '@angular/forms';
import { AlertService } from './../services/alert.service';
import { UserService } from './../services/user.service';
@Injectable({
providedIn: 'root'
})
export class ValidationService {
availableUsername: boolean;
availableEmail: boolean;
constructor(
private alertService: AlertService,
private userService: UserService
) { }
validateUsername(controls: any): boolean {
const username = controls.username.value;
this.isUsernameAvailable(username);
if (!this.availableUsername) {
this.alertService.error('This username is already taken', false);
return true;
}
return false;
}
private isUsernameAvailable(username: string) {
if (username === undefined || username === '') {
return;
}
this.userService.isUserNameAvailable(username)
.subscribe((result) => {
this.availableUsername = result;
},
error => {
this.alertService.error(error);
return;
});
}
}
userService.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { environment } from './../../environments/environment';
@Injectable({ providedIn: 'root' })
export class UserService {
apiUrl: string = environment.apiUrl;
constructor(private http: HttpClient) { }
isUserNameAvailable(username: string) {
return this.http.get<boolean>(`${this.apiUrl}/users/checkUsernameAvailability/${username}`);
}
}