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

Ensure data accuracy by triggering the cache - implementing SWR hook in Next.js with TypeScript

I recently implemented the swr hook in my next.js app to take advantage of its caching and real-time updates, which has been incredibly beneficial for my project (a Facebook clone). However, I encountered a challenge. The issue arises when fetching public ...

Acquiring JSON-formatted data through the oracledb npm package in conjunction with Node.js

I am currently working with oracledb npm to request data in JSON format and here is the select block example I am using: const block = 'BEGIN ' + ':response := PK.getData(:param);' + 'END;'; The block is ...

Error Uncovered: Ionic 2 Singleton Service Experiencing Issues

I have developed a User class to be used as a singleton service in multiple components. Could you please review if the Injectable() declaration is correct? import { Injectable } from '@angular/core'; import {Http, Headers} from '@angular/ht ...

Angular 8 Refresh Token Implementation

I am currently working on an Angular 8 app that is integrated with .NET Core. My goal is to find a way to refresh a JWT token within the application. Within the integration, users are able to validate and receive a token which expires after 30 minutes. T ...

Can you use getters and setters in a TypeScript declaration file?

I am facing an issue with a declaration file for the openUi framework. The framework utilizes a get<propname>() and set<propname>(var) syntax for its properties. In traditional JavaScript, the setup would look like this: sap.ui.getCore().atta ...

Issue with the physical back button on Android devices

Whenever I press the physical Android Button I encounter the following error: While executing, an unhandled exception java.lang.IndexOutOfBoundsException: setSpan (2..2) goes beyond length 0 Here is my app.routing.ts import { LoginComponent } from " ...

Issue in Ionic 2: typescript: The identifier 'EventStaffLogService' could not be located

I encountered an error after updating the app scripts. Although I've installed the latest version, I am not familiar with typescript. The code used to function properly before I executed the update. cli $ ionic serve Running 'serve:before' ...

Issue with esbuild not executing within docker compose configuration

Currently, I am new to using esbuild and struggling to set up a script that can watch and rebuild my files. Additionally, I need this functionality to work within a docker environment. Within my package.json file, the following scripts are defined: " ...

It is advisable for the subscriber not to halt upon encountering an error within the

Dealing with a problematic subscriber that automatically unsubscribes itself when an error occurs: observable .subscribe( (data) => { // logic encountering an error // similar to throw new Error() } ) To avoid this, I can use t ...

React: Function is missing a return type declaration. eslint plugin @typescript-eslint urges for explicit function return types

I'm just starting out with Typescript in React. I've created a simple functional component, but eslint is giving me an error saying that the return type for the functional component itself is missing. Can anyone help me figure out what I'm d ...

Encountering 404 errors when reloading routes on an Angular Azure static web app

After deploying my Angular app on Azure static web app, I encountered an error. Whenever I try to redirect to certain routes, it returns a 404 error. However, if I navigate from one route to another within the app, everything works fine. I have attempted t ...

Using TypeScript with Node.js and Sequelize - the process of converting a value to a number and then back to a string within a map function using the OR

Currently, I am facing a challenge in performing addition on currency prices stored as an array of objects. The issue arises from the fact that the currency type can vary among 3 different types within the array of objects. The main hurdle I encounter is ...

Having trouble getting undefined values for keys while attempting to retrieve all the data from Firebase DB with Angular

Currently, I have code that is fetching records from the Firebase database using both Angular and Ionic. The code functions properly, but it does not provide me with the keys for each record. Instead, it returns 'undefined'. I have researched s ...

Error: The property you are trying to set is undefined and cannot

When I attempt to set a property 'error' that is undefined, I receive a TypeError. The problematic line of code looks like this: this.error = error.code; This issue arises in an Angular Reactive Form while making a call to a web service. Below i ...

`Browser Extension Compatibility``

I am currently working on developing a TypeScript extension that is compatible with all major browsers. I have come across the package https://www.npmjs.com/package/web-ext-types which I have integrated into my package.json file. While coding in TypeScrip ...

Create a prop type that can be either a single number or an array of numbers, depending on the value of another

Seeking a solution, I am exploring an example using arrays with the 'multi' property. When 'multi' is true, the items should be of type number[]. Otherwise, they should be of type number. interface EnhancedSelectProps { items: multi ? ...

What is the best way to implement lazy loading for child components in React's Next.js?

I am exploring the concept of lazy loading for children components in React Next JS. Below is a snippet from my layout.tsx file in Next JS: import {lazy, Suspense} from "react"; import "./globals.css"; import type { Metadata } from &quo ...

SystemJS is loading classes that are extending others

In my Angular2 application, I have two classes where one extends the other. The first class is defined in the file course.ts (loaded as js) export class Course { id:string; } The second class is in schoolCourse.ts (also loaded as js) import {Cours ...

Angular form requests can utilize the Spring Security Jwt Token to allow all options methods

Despite checking numerous sources online, I am facing a persistent issue with my Angular application. The problem arises when using HttpClient along with an Angular interceptor to set headers for authentication in my Java Rest API using JWT tokens. The int ...

Error encountered while attempting to generate migration in TypeORM entity

In my project, I have a simple entity named Picture.ts which contains the following: const { Entity, PrimaryGeneratedColumn, Column } = require("typeorm"); @Entity() export class Picture { @PrimaryGeneratedColumn() ...