Reputation: 161
Motive : I am doing a validation on book name during save - if there is already a book in the DB with the same name, validation error message should be thrown. I have a method in my service that returns the books object if any books are present with the user entered book name.
After I call this service method I subscribe to it, assign the result to a bool variable and check the bool variable in if statement. since using subscribe/ observable, the if statement executes first and then the subscriber is getting called and the correct value is not returned and validation is not firing.
Where am I going wrong ? Thanks in advance.
Below is my code :
export class AddBooksComponent implements OnInit{
bookName = "";
isError = false;
errorMessage="";
isPresent:boolean = false;
constructor(public bsModalRef: BsModalRef,private booksService: BooksService) { }
ngOnInit(): void { }
saveBooks() {
if(this.checkBookExistenance()) {
this.isError = true
this.errorMessage="The provided book name is already exists."
} else {
this.bsModalRef.hide()
}
}
checkPreferenceExistenance():boolean {
this.booksService.getBookByName(bookNameName:trim(this.bookName))
.pipe(first())
.subscribe((data) => {
// if the response has data then the book is present
if(data.length) {
isPresent= true;
}
else{
isPresent= false;
}
});
return isPresent;
}
}
Upvotes: 0
Views: 712
Reputation: 2361
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()
}
}
);
Upvotes: 1