Executing multiple HTTP requests in Angular using the HttpClient

Recently, I came across a concerning issue in my Angular 5 App.

It all started with this simple call in my service:

interface U{
  name:string;
}
...

constructor(private http : *Http*, private httpC:HttpClient) // Http is deprecated - its a compare test

...
ping() //Test Debug func
  {
    let o:Observable<U> = this.httpC.get<U>(this.url + "user/1");

    o.subscribe(resp => {
      console.log("SUBSCRIBE1: Init:get:user:U: " + resp.name);
      return resp;
    },
    this.handleError);

    o.subscribe(resp => {
      console.log("SUBSCRIBE2: Init:get:user:U: " + resp.name);
      return resp;
    },
    this.handleError);

    o.toPromise().then(resp => {
      console.log("PROMISE: Init:get:user:U: " + resp.name);
      return resp;
    });
  }

Upon calling the ping() function, the Angular/Browser seems to be making three separate calls to "url/user/1" One for each listener (2 subscribes, 1 promise)

Is this normal behavior?

I always thought an Observer allows multiple "Listeners" to wait for an action, not trigger it.

Can someone please provide some clarity or an example of how to handle this situation correctly? Any guidance would be greatly appreciated!

EDIT: Adding further experimentation with a similar call using the deprecated HTTP client yields the same results. It appears to be intentional design. However, I'm still unsure of how to listen without triggering multiple calls.

 ping() //Test Debug func
  {
    let o:Observable<U> = this.httpC.get<U>(this.url + "user/1");

    o.subscribe(resp => {
      console.log("SUBSCRIBE1: Init:get:user:U: " + resp.name);
      console.log(resp);
      //this.currentUser = resp;
      return resp;
    },
    this.handleError);

    o.subscribe(resp => {
      console.log("SUBSCRIBE2: Init:get:user:U: " + resp.name);
      console.log(resp);
      //this.currentUser = resp;
      return resp;
    },
    this.handleError);

    o.toPromise().then(resp => {
      console.log("PROMISE1: Init:get:user:U: " + resp.name);
      console.log(resp);
      //this.currentUser = resp;
      return resp;
    });

    o.toPromise().then(resp => {
      console.log("PROMISE2: Init:get:user:U: " + resp.name);
      console.log(resp);
      //this.currentUser = resp;
      return resp;
    });


    let call:string = this.url + "user/1";
    return this.http.get(call)
        .toPromise()
        .then(resp => {
          console.log("OLD HTTP PROMISE 1 " + resp);

          return resp;
        })
        .catch(this.handleError)
        .then(resp => {
          console.log("OLD HTTP PROMISE 2 " + resp);

          return resp;
        });
  }

The network activity shown by Chrome after a single ping call can be seen here:

https://i.stack.imgur.com/mLEp0.png

Answer №1

My concept of an Observer involves adding multiple "Listeners" that wait for an action to occur, rather than directly triggering the action.

You might be mistaking subscribe() with a promise's then(). Unlike promises, where subsequent calls to then return the same result, calling subscribe() on a ''cold'' observable will create a new "producer" with each call and generate a distinct result each time. To understand more about hot and cold observables, check out this insightful article by Ben Lesh.

Is there something wrong in my configuration after the update?

The behavior I mentioned also applies to your example using HttpClient's get(): It produces a cold observable where the request is recreated on every call.

To make the client's "cold" http-request observable "hot," you can share the observable's source/sequence using rxJS share() or preferably shareReplay, which allows you to replay values.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

declaration of function interface and property that cannot be modified

After reviewing some new TypeScript code, I encountered a part that left me puzzled. interface test { (a: number): number; readonly b: number; } While I understand that (a:number): number signifies a function where the argument is a:number and the ret ...

Uncovering the enum object value by passing a key in typescript/javascript

How can I retrieve the value of an enum object by passing the key in typescript? The switch case method works, but what if the enum object is too long? Is there a better way to achieve this? export enum AllGroup = { 'GROUP_AUS': 'A' &a ...

Encountered a type error during project compilation: "Type '(e: ChangeEvent<{ value: string[] | unknown; }>) => void' error occurred."

I recently started working with react and I'm facing an issue with a CustomMultiSelect component in my project. When I try to call events in another component, I encounter the following error during the project build: ERROR: [BUILD] Failed to compile ...

When using Angularfire, the function to switch the type from snapshotChanges will consistently return the value as "value"

At this moment, when I use the Angularfire extension to call the following code: this.db.doc(path).snapshotChanges(); Angularfire always retrieves a DocumentSnapshot with a type that is consistently "value", regardless of the actual change type. Is there ...

Guidelines for creating a binary release of Node.js with native modules

Currently, I am in the midst of exploring the world of Node.js projects, delving into different bundlers and various other components. One interesting concept that came to mind is the idea of bundling Node.js into a single binary for Linux, macOS, or Windo ...

What is the syntax for using typeof with anonymous types in TypeScript?

After reading an article, I'm still trying to grasp the concept of using typeof in TypeScript for real-world applications. I understand it's related to anonymous types, but could someone provide a practical example of how it can be used? Appreci ...

Next.js is experiencing issues with the build process

I encountered an issue while working on a Next.js project with NextAuth.js. The problem arises when I try to define my authOptions, as a TypeScript error indicates that the object is not compatible with the expected type for AuthOptions. Here's the sn ...

The function 'transformArticles' is not recognized as a property of the object 'Article'

I'm encountering an issue with Typescript that I need help understanding. In my code, I have a route where I am importing a class called Article like this: import { Request, Response } from "express"; const appRoot = require("app-root-path"); import ...

Angular - How to fix the issue of Async pipe not updating the View after AfterViewInit emits a new value

I have a straightforward component that contains a BehaviorSubject. Within my template, I utilize the async pipe to display the most recent value from the BehaviorSubject. When the value is emitted during the OnInit lifecycle hook, the view updates correc ...

Typescript navigation and Next.js technology

Currently, I am in the process of learning typescript and attempting to create a navigation bar. However, I encountered an error message stating "Unexpected token header. Expected jsx identifier". I am a bit puzzled by this issue. Could someone kindly pro ...

Is it possible to extend the Object class in order to automatically initialize a property when it is being modified?

My experience with various programming languages leads me to believe that the answer is likely a resounding no, except for PHP which had some peculiar cases like $someArray['nonexistentKey']++. I'm interested in creating a sparse object whe ...

Setting up TypeScript in Node.js

A snippet of the error encountered in the node.js command prompt is as follows: C:\Windows\System32>npm i -g typescript npm ERR! code UNABLE_TO_VERIFY_LEAF_SIGNATURE npm ERR! errno UNABLE_TO_VERIFY_LEAF_SIGNATURE npm ERR! request to https:/ ...

Arranging Angular Array-like Objects

I am in possession of an item: { "200737212": { "style": { "make": { "id": 200001510, "name": "Jeep", "niceName": "jeep" }, "model": { "id": "Jeep_Cherokee", "name": "Cherokee", "nice ...

Discover the unseen: The ultimate guide to detecting visible objects in a (deferLoad) event

I'm utilizing the (deferLoad) method to load an image gallery in a more controlled manner. Is there any event available that can inform me about which items are currently visible? The main goal is to load a set of data along with an image path, and t ...

Form: Initiate a manual valueChange

Currently, I am in the process of constructing a form using FormBuilder. My goal is to invoke another function whenever one of my FormControl elements is updated. To achieve this, I have opted to utilize valueChanges. However, I am facing an issue where I ...

The AngularJS 2 TypeScript application has been permanently relocated

https://i.stack.imgur.com/I3RVr.png Every time I attempt to launch my application, it throws multiple errors: The first error message reads as follows: SyntaxError: class is a reserved identifier in the class thumbnail Here's the snippet of code ...

Guide to creating two-way data binding using ngModel for custom input elements like radio buttons

I am currently facing an issue with implementing a custom radio button element in Angular. Below is the code snippet for the markup I want to make functional within the parent component: <form> <my-radio [(ngModel)]="radioBoundProperty" value= ...

How can we strengthen the type checking when defining the sorting function for json properties?

When dealing with a json structure from a service that contains .attributes json values, I often find myself needing to sort either by id from the DTO or by several attributes from the IContactsAttributes. The microservice returns this specific structure: ...

Ways to eliminate unnecessary items from a JavaScript object array and generate a fresh array

My JavaScript object array contains the following attributes: [ { active: true conditionText: "Really try not to die. We cannot afford to lose people" conditionType: "CONDITION" id: 12 identifier: "A1" ...

Encountering difficulty creating a new entity in NestJS with TypeORM due to the error message EntityMetadataNotFoundError

Hey, I've been encountering some issues with TypeORM. I'm attempting to add a new entity to my current project and here's what I did: I created a new entity import { Entity, Column, PrimaryGeneratedColumn, JoinColumn, OneToOne } from ' ...