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

545
Vistas
how to wait http response in observable (rxjs)

This is the original code.

// info.service.ts.  

  this.info$ = new BehaviorSubject<Info>(null);

  async getInfo() {
    try {
      const info = await this.infoApi.getInfo();
      console.log(info) // info {name: 'sdf', 'age': 12}
      this.info$.next(info);
    } catch {
      this.info$.next(null);
    }
  }



  // infoApi Class
  getInfo() {
    return this.apiService.get<Info>(`/info`, this.infoService....);
  }

For asynchronous processing using rxjs, we modified the code as follows. Other asynchronous processing codes in my project have also been modified to rxjs in the following way, and they are working fine. However, only the getinfo service does not work properly. Asynchronous processing is not progressing properly. As a result of checking the network panel, the info data request is checked in the managed state. Please let me know if there are any expected problems.
(Async, wait is not available, so I'm trying to use Rxjs. )

Both versions of code do not work as expected.

first version

// info.service.ts
  getInfo() {
    from(this.infoApi.getInfo()).subscribe(
      info => {this.info$.next(info); 
      console.log(info) // null
      error => {this.info$.next(error)
      }
    )
  }

  // infoApi Class
  getInfo() {
    return this.apiService.get<Info>(`/info`, this.infoService....);
  }

// api.service.ts
  get<T>(url: string, opts?: options) {
    return this.request<T>('GET', url, null, opts);
  }

second version

// info.service.ts
  getInfo() {
   this.infoApi.getInfo().subscribe(
      info => {this.info$.next(info); 
      console.log(info) // null
      error => {this.info$.next(error)
      }
    )
  }

  // infoApi Class
  getInfo() {
    return from(this.apiService.get<Info>(`/info`, this.infoService....);
  }

// api.service.ts
  get<T>(url: string, opts?: options) {
    return this.request<T>('GET', url, null, opts);
  }
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

The getInfo() returns an Observable, there is no need to use from() in your info.servive.ts.

Also the formatting in the subscribe section could be:

  getInfo() {
    this.infoApi.getInfo()
    .subscribe({
      next: (info => {this.info$.next(info); 
      console.log(info)}), // null
      error: (error => this.info$.next(error))
      }
    )
  }

I've constructed a little example using randomAPI

info.service.ts

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
import { tap } from 'rxjs/operators';

// Using random data api for example
export type Info = {
  blend_name: string;
};

@Injectable({
  providedIn: 'root',
})
export class infoApiService {
  info$: BehaviorSubject<Info> = new BehaviorSubject<Info>(null);

  constructor(private http: HttpClient) {
    // Use subscription for making BehaviorSubject work...
    this.getInfo().subscribe()
  }

  getInfo() {
    return this.http
      .get<Info>('https://random-data-api.com/api/coffee/random_coffee')
      .pipe(
        tap({
          next: (info) => {
            this.info$.next(info);
            console.log('logging in tap', info);
          },
          error: (error) => this.info$.error(error),
        })
      );
  }
}

app.component.ts

import { Component, OnInit, VERSION } from '@angular/core';
import { Observable } from 'rxjs';
import { Info, infoApiService } from './info.service';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {

  infoObs$!: Observable<Info>;

  constructor(private info: infoApiService) {
    this.infoObs$ = this.info.info$.asObservable();
  }
}

app.component.html

<div *ngIf="infoObs$ | async">
  <h3>The info is here : {{ (infoObs$ | async).blend_name }}</h3>
</div>

It's available in StackBlitz: https://stackblitz.com/edit/angular-ivy-wgjsfa?file=src%2Fapp%2Fapp.component.html,src%2Fapp%2Fapp.component.ts,src%2Fapp%2Finfo.service.ts

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