purplefeel
purplefeel

Reputation: 193

Angular Observable subscribes multiple times occasionally

I see there are many questions already asked about this issue but still can't find correct solution.

I have a service for http request and subrcribe in the component.

It sometimes subscribes several times and send several http requests.

Sometimes it works fine so I am not sure what it depends on whether it is called several times or not.

http request is called 3 times

The first one is checking option. (I am not sure this is required or its because of CORS policy. Is there a way to avoid this too?)

first request

And then the next two requests are the same and return the values twice.

This is a big trouble for me.

This is my service and component code.

service.ts

getPartners(): Observable<Partner[]> {
    return this.http.get<Partner[]>(SERVER_API_URL + `api/partners`);
  }

component.ts

this.partnerService.getPartners()
    .pipe(first())
    .subscribe(partners => {
      this.partners = partners;
    });

How can I fix this? Thanks in advance.

Upvotes: 2

Views: 465

Answers (1)

alejoko
alejoko

Reputation: 1110

The first call is due to your request is not simple. A simple request is those who match de following:

  • GET / HEAD / POST
  • Uses just a few values for headers: ex. Content-type, Accept-Language, Accept, etc.. (see list on the internet)
  • no ReadableStream used.
  • etc...

This means that, if you for example (typical case) use the auth by injecting an authorization header on the HTTP request, this call would turn into a NOT SIMPLE call and would fire a preflight call previous the original one (this the OPTIONS call). Wich is automatically fired by the browser, and you cannot stop/skip this.

Upvotes: 1

Related Questions