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

2.4K
Visualizações
Angular 2 observable subscribing twice executes call twice

Problem
I subscribe to an httpClient.get observable twice. However, this means that my call gets executed twice. Why is this?

Proof
For every subscribe() I do, I get another line in the login page.

Code (onSubmit() from login page button)

var httpHeaders = new HttpHeaders()
  .append("Authorization", 'Basic ' + btoa(this.username + ':' + this.password));

var observable = this.httpClient.get('api/version/secured', { headers: httpHeaders});
observable.subscribe(
  () => {
    console.log('First request completed');
  },
  (error: HttpErrorResponse) => {
    console.log('First request error');
  }
);
observable.subscribe(
  () => {
    console.log('Second request completed');
  },
  (error: HttpErrorResponse) => {
    console.log('Second request error');
  }
);

Console

zone.js:2935 GET http://localhost:4200/api/version/secured 401 (Unauthorized)
login.component.ts:54 First request error
zone.js:2935 GET http://localhost:4200/api/version/secured 401 (Unauthorized)
login.component.ts:62 First request error

Irrelevant background
I have a LogonService object which handles al my login functionality. It contains a boolean variable that shows whether I am logged in or not. Whenever I call the login function, it subscribes to the observable of the httpClient.get, to set the login variable to true or false. But the login function also returns the observable, which gets subscribed to. Took me some time to link the double request to the double subscription. If there is a better way of tracking the login than through a variable, let me know! I am trying to learn angular :)

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

0

You may use the share operator on your result from HttpClient.get, like this:

var observable = this.httpClient.get('api/version/secured', { headers: httpHeaders })
  .pipe(share());

You'll need to add the following import on top of your script:

import { share } from 'rxjs/operators';

The share operator makes an observable hot, i.e. shared between subscribers. But there's a lot more to it, I would suggest this article to dive deeper (you can of course also google up hot vs cold observables to find more).

over 4 years ago · Santiago Trujillo Relatório

0

Your observable is cold:

An observable is cold if the producer of its notifications is created whenever an observer subscribes to the observable. For example, a timer observable is cold; each time a subscription is made, a new timer is created.

You need to multicast your Observable, or in other words, to make it hot:

An observable is hot if the producer of its notifications is not created each time an observer subscribes to the observable. For example, an observable created using fromEvent is hot; the element that produces the events exists in the DOM — it’s not created when the observer is subscribed.

For this you can use share operator, but it still cannot guarantee you a single http call. Share will multicast your observable, making it shared between the subscribers, but once the http call completes it will make a new http call for new subscribers.

If you want a caching behavior (performing the call once and then providing the value to each subscriber whenever it subscribes) you should use publishReplay().refCount().

Further reading:

Publish and share operators

over 4 years ago · Santiago Trujillo Relatório

0

In addition to the above answers, you can assign to observable your http service and then subscribe to the get data. For example:

export class App implements OnInit {

lessons$: Observable<Lessons[]>;

constructor(private lessonsService: lessonsService) {

}

ngOnInit() {
    this.lessons$ = this.lessonsService.loadLessons().publishLast().refCount();

    this.lessons$.subscribe(
         () => console.log('lessons loaded'),
         console.error
         );
    }
}

The Angular documentation.

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