Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

138
Vistas
Angular typescript subscribing to a variable does not give correct results

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;
  }
}
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

this.booksService.getBookByName() is asynchonous, it takes some time to execute, in the meantime the code procedes. checkBookExistenanceshould 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()
        }
      }
    );
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda