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

194
Views
Mi valor observable no se muestra a pesar de ngOnInit

Pido disculpas en primer lugar por mi inglés, que no es nada bueno. ¡Hoy pido su ayuda porque tengo un problema incomprensible!

Actualmente estoy en Angular y uso .subscribe para rastrear mis observables. Aquí está mi componente:

 export class SiteDetailComponent implements OnInit { public test1 : ISite = <ISite>{}; public test2: ISite[] = []; public errMsg : string = ""; constructor(...) ngOnInit() { const id : number = Number(this.route.snapshot.paramMap.get('id')); this.SiteListeService.getSiteById(id).subscribe({ next: site => { this.test1 = site; }, error: err => this.errMsg = err }); this.SiteListeService.getSites().subscribe({ next: sites => { this.test2 = sites; }, error: err => this.errMsg = err });

Como puede ver, hice un .subscribe en 2 Observable: this;SiteListeService.getSites() y this.SiteListeService.getSiteById(id), aquí está el servicio en cuestión (que he importado el constructor).

 public getSites(): Observable<ISite[]> { return this.http.get<ISite[]>(this.HOTEL_API_URL + "test/").pipe( tap(test2 => console.log('test2 : ', test2)), catchError(this.handleError) ); } public getSiteById(id : number): Observable<ISite> { return this.http.get<ISite>(this.HOTEL_API_URL + "test/" + id).pipe( tap(test1 => console.log('test1 : ', test1)), catchError(this.handleError) ); }

El problema es que la variable test1 que uso en mi .html no quiere mostrarse, aquí está el ejemplo:

 <h5 class="card-title">{{ test1.nom }} </h5>

Por otro lado mi variable test2 que uso en el mismo .html funciona, ejemplo:

 <div class="col mb-4" *ngFor="let t2 of test2"> <h5 class="card-title">{{ t2.nom }}</h5>

¡Lo que no entiendo es por qué uno muestra y el otro no! ¡Sin embargo, puse ambos en ngOnInit() para que se trate con prioridad!

en mi servicio hice un console.log de lo que me devuelven mis solicitudes https, y todo funciona correctamente... Esto es lo que me muestra la consola de Google Chrome:

ingrese la descripción de la imagen aquí

Espero haberte proporcionado toda la información necesaria, disculpa si mis palabras no son correctas, no soy un profesional. ¡Gracias de antemano por leer!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Suponiendo que el método de servicio getSiteById estaba en la línea 30 cuando recibió las entradas de registro de su mensaje, la solicitud http está devolviendo una matriz:

ingrese la descripción de la imagen aquí

Sus funciones esperan un objeto en su lugar. Entonces, cuando asigna su variable test1 aquí:

 this.test1 = site;

se convierte en una matriz con un solo elemento.

Hay algunas opciones para resolver esto:

  1. cambiarlo para obtener el primer elemento
 this.test1 = site[0];
  1. esto también podría hacerse en la función de servicio
 public getSiteById(id : number): Observable<ISite> { return this.http.get<ISite[]>(this.HOTEL_API_URL + "test/" + id).pipe( map(data => data[0]), catchError(this.handleError) ); }
  1. cambie su BackEnd para esta solicitud para que devuelva el elemento y no una matriz.
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!