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

422
Visualizações
Any Scenario(s) that RXJS Observable Subscribe wont trigger either success and error

This is more like question than resolve a problem.
I would like to know if there any scenario that both "Success" and Error" is not triggered.

The post call to "/logout" will result Http status return code 200 with empty respond body which is expected

import { httpClient } from angular/common/http;
private http: HttpClient;

this.http.post<any>('/logout', {})
      .subscribe(
      () => {
        console.log("Logout");
      }, error => {
        console.log(error);
      },
      () => {
        console.log("Finally");
      });

It will output "Finally" 100% of time. That means success and error is not triggered at all.

Is there possibilities that either success and error not trigger. And clearly the http status code response is 200 OK.

Update: The answer that @meriton provided work great.

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Observable, in general, are not required to complete or error. They may remain live, and continue to emit values, forever.

However, Observable returned by HttpClient are guaranteed to terminate with either success or error (though the error may take a few minutes in case of a timeout) according to the HTTP status of the response. The presence of absence of a body does not affect this. If the request is successful, the observable will emit exactly one value: the response body (or null if the response body is absent).

I can not reproduce your claim that "success or error is not triggered at all". May you have misunderstood what the callbacks mean? When you provide three callbacks to subscribe, they are, in order:

  • the next callback, which receives emitted values
  • the error callback, which notifies that the Observable has aborted due to an error
  • the complete callback, which notifies that the Observable has completed successfully

The danger of mixing up callbacks is one reason why the RXJS team has deprecated passing several callbacks as separate arguments to subscribe in RXJS 8. The future proof way to write your code would be:

this.http.post<any>('/logout', {}).subscribe({
  complete: () => {
    console.log("Logout successful")
  },
  error: (error) => {
    console.log(error);
  }
});

BTW, none of these callbacks mean "finally", as in the finally clause of a try-statement, which is executed both in case of success and error. If you want to do something irrespective of whether the Observable completed successfully or failed with an error, you could use the finalize operator.

over 4 years ago · Santiago Trujillo Relatório

0

  1. http library success depends on Status:200, it does not require message.body to be present

  2. Example code of using RXJS pipe flow, where you can control the flow by capturing success & error, controlling timeout. It also demonstrates how you can use .subscribe() method as classic Finally

Example RXJS Flow:

 this.http
      .post<any>('/logout',{})
      .pipe(
        map(() => {                 // OK
          return { success: true, err: null }; 
        }),
        timeout(10000),             // CONTROL TIMEOUT
        catchError((e) => {         // IN CASE OF ERROR
          return of({success: false, err:e});
        })
      )
      .subscribe((result) => {        // FINALLY here
        if (result.success) {
          console.log('Logged out successfully');
        } else {
          console.log('Logout failed', result.err); 
        }
      });
over 4 years ago · Santiago Trujillo 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