In my backend - express.js I am successfully returning a boolean value which tells me if a user exists or not.
Problem is in my frontend - angular(newest version), when I receive that value, I need to use that value right after asynchronous execution.
So I decided to use RxJS pipe + map
I get this:
Argument of type 'Observable<unknown>' is not assignable to parameter of type 'OperatorFunction<boolean, unknown>'.
Type 'Observable<unknown>' provides no match for the signature '(source: Observable<boolean>): Observable<unknown>'.ts(2345)
The 'this' context of type 'void' is not assignable to method's 'this' of type 'Observable<unknown>'.
ApiService.ts
checkIfUserExists(email: string): Observable<boolean> {
return this.http.get<boolean>(`${this.COINS_URL}/login/check/${email}`);
}
register.component.ts
let value = null
this.apiService.checkIfUserExists(this.user.email)
.pipe(
map(data => console.log(data))
)
console.log(value) -- returns [object Object]
How do I resolve this issue and use pipe + map successfully ?
Edit for comments:
checkIfUserExists() {
this.user = this.userRegistrationForm.value
return this.apiService.checkIfUserExists(this.user.email)
.pipe(
map(data => data))
.subscribe(e => e.userExists)
}
When trying to use - I get [object Object]
userExists = this.checkIfUserExists()
console.log('userExists: ' + userExists)
Edit 2: Final solution, thanks for all the help Problem was solved using callbacks Big thanks to this post: How do I return the response from an asynchronous call?
Code:
checkIfUserExists(callback) {
this.user = this.userRegistrationForm.value
console.log("2. callback here is the function passed as argument above...")
this.apiService.checkIfUserExists(this.user.email)
.pipe(
map(data => data))
.subscribe(e => {
console.log("3. start async operation...")
console.log("4. finished async operation, calling the callback, passing the result...")
callback(e.userExists)
})
}
onSubmit() {
let userExists = null
console.log("1. function called...")
this.checkIfUserExists((result: boolean) => {
// 5. Received the result from the async function,
// now do whatever you want with it:
console.log("5. result is: ", result);
userExists = result
this.userExistsValidator(userExists)
});
}