I am attempting to verify the existence of a user in an Angular's in-memory API by validating their username. The function checkUsernameExists(username)
is supposed to return an Observable<boolean>
based on whether the API responds with undefined or a user object. However, I am encountering an issue where it always returns false regardless of whether the username exists or not. I have confirmed that the getUser()
function works correctly as it returns undefined for non-existing users and a user object for existing ones.
If possible, I would prefer to only make adjustments to the checkUsernameExists
function. This function is used for an async validator that is currently functioning properly. I have searched extensively for a solution to this problem but have been unable to find anything that is not deprecated or does not meet the requirements for it to work effectively.
usersUrl = '/api/users';
constructor(private http: HttpClient) {}
users = this.http.get<User[]>(this.usersUrl).pipe(shareReplay());
// retrieves a user object when subscribed to
getUser(username: string): Observable<User | undefined> {
return this.users.pipe(
take(1),
map((users: User[]) => {
return users.find((user) => user.username === username);
})
);
}
// checks if user exists
checkUsernameExists(username: string): Observable<boolean> {
var userValid = false;
this.getUser('<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a4c0d1c9c9ddd1d7c1d6e4c0d1c9c9dd8ac0d1c9">[email protected]</a>')
.pipe(take(1)).subscribe(
result => {
if (result === undefined) {
console.log('result: ', result);
return (userValid = false);
} else {
console.log('result: ', result);
return (userValid = true);
}
}
);
console.log(userValid) // regardless of the username, the value always remains the same as its initialization (false)
return of(userValid);
}