Motivo: estoy haciendo una validación del nombre del libro durante el guardado; si ya hay un libro en la base de datos con el mismo nombre, se debe generar un mensaje de error de validación. Tengo un método en mi servicio que devuelve el objeto de los libros si hay algún libro presente con el nombre del libro ingresado por el usuario.
Después de llamar a este método de servicio, me suscribo a él, asigno el resultado a una variable bool y verifico la variable bool en la instrucción if. ya que al usar subscribe/observable, la declaración if se ejecuta primero y luego se llama al suscriptor y no se devuelve el valor correcto y la validación no se activa.
¿Dónde me estoy equivocando? Gracias por adelantado.
A continuación se muestra mi código:
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; } }this.booksService.getBookByName() es asíncrono, lleva algún tiempo ejecutarlo, mientras tanto, el código continúa. checkBookExistenance debería devolver un 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) ); }y entonces:
this.checkPreferenceExistenance().subscribe( exist => { if (exist) { this.isError = true this.errorMessage = "The provided book name is already exists." } else { this.bsModalRef.hide() } } );