Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

136
Views
La escritura de mecanografiado angular que se suscribe a una variable no da resultados correctos

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; } }
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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() } } );
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!