Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

553
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda