Angular typescript subscribing to a variable does not give correct results
this.booksService.getBookByName()
is asynchonous, it takes some time to execute, in the meantime the code procedes.
checkBookExistenance
should return an observable:
checkPreferenceExistenance(): Observable<boolean> {
return this.booksService.getBookByName(bookNameName: trim(this.bookName)).pipe(
first(),
map(data => {
if (data.length){
return true;
}else{
return false;
}
})
// or shortform without if/else: map(data => data.length)
);
}
and then:
this.checkPreferenceExistenance().subscribe(
exist => {
if (exist) {
this.isError = true
this.errorMessage = "The provided book name is already exists."
} else {
this.bsModalRef.hide()
}
}
);