Performing both HTTP requests with a single subscribe function in Angular 4

I'm facing an issue with the following code:

ComputerValue: number;
private subscription: ISubscription;

ngOnInit() {
  this.getMyValue();
  setInterval(() => {
    this.getMyValue();
  }, 30000);
}


getMyValue(): void {
  this.subscription = this.dataService.getValueOfComputer().subscribe(data => {
    console.log(data);
    this.ComputerValue = data;
  });
}

After checking my console, I noticed that the result is being displayed twice because it seems like my HTTP query inside the subscribe function is executing twice. This has been puzzling me.

https://i.sstatic.net/NFGca.png

Any suggestions on how to resolve this?

Thank you in advance!

Answer №1

Using setTimeout instead of setInterval may be more appropriate in this case. The getMyValue method will still get called every 30 seconds.

It seems that the getMyValue method is being called twice. Once inside the ngOnInit and then again within the setInterval of ngOnInit.

To streamline your code, you can make the following changes:

ComputerValue: number;
private subscription: ISubscription;

ngOnInit() {
  setInterval(() => {
    this.getMyValue();
  }, 30000);
}


getMyValue(): void {
  this.subscription = this.dataService.getValueOfComputer().subscribe(data => {
    console.log(data);
    this.ComputerValue = data;
  });
}

If you're experiencing multiple console logs, it might be due to memory leaks. Consider unsubscribing from the subscription by implementing the following:

FIX

Before making any further modifications, be sure to add the unsubscribe method to properly manage subscriptions. This can help prevent multiple logs appearing in the console.

ngOnDestroy() {
  this.subscription && this.subscription.unsubscribe();
}

Note: To replicate the issue, try commenting out the ngOnDestroy method and observe the behavior when changing console log contents without periodic intervals.

Answer №2

RESOLVED

In my project, I had two components - AppComponent and ExampleComponent. The issue described above was related to ExampleComponent.

To resolve the problem, I made sure to include ExampleComponent in the NgModule by adding it to both the declarations and Bootstrap array as shown below:

@NgModule({
    imports: [BrowserModule, HttpClientModule, BrowserAnimationsModule, FormsModule, ChartsModule],
    declarations: [AppComponent, ExampleComponent],
    bootstrap: [AppComponent, ExampleComponent],
    providers:[DataService]
})

The key solution was removing ExampleComponent from the Bootstrap Array, which successfully stopped the duplication of HTTP requests.

If anyone has additional insights on this matter, please feel free to share your thoughts.

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

Transform coordinated universal time to the corresponding local time using Angular

Looking to transform the UTC format date into an India date and time format using Angular 2019-02-18T17:31:19-05:00 I am looking for it to be in the following format: DD/MM/YYYY HH:MM(eg: 02/19/2019 04:01 AM). Any guidance on how to accomplish this would ...

Showing nested information from an observable within an Angular 2 template

Currently, I am utilizing a service that manages application state using BehaviorSubjects in Rx, which then exposes Observables for components to interact with. Within one of my components, the goal is to display nested data if it exists. Here is the code ...

Updating the node startup file with Visual Studio 2015 using NodeJS/Typescript

Encountering a persistent error: Error Code: TS5055 Cannot write file C:/project/dir/server.js' because it would overwrite the input file. Project: TypeScript/JavaScript Virtual Projects Even after renaming my entry filename to nodeserver.js, the ...

What should be the output when ending the process using process.exit(1)?

I need to update my code by replacing throw new Error('Unknown command.') with a log statement and process.exit(1);. Here is the example code snippet: private getCommandByName = (name: string): ICommand => { try { // try to fetch ...

Utilizing MySQL Data in an Angular 2 Front-End Component within an Electron Desktop Application

Being new to Electron, this is my first attempt at creating a desktop app. One section of the application simply displays current forecasts based on customer data retrieved using standard database queries. I've opted to use a local MySQL database to ...

How can I transfer a JSON array to a custom element in Angular?

Having trouble passing a JSON array in an angular component (custom element). The code includes looping through the JSON array and setting up the array data in @Inject. Here's an example: Import { Input, Component, ViewEncapsulation, EventEmi ...

Having trouble with an Angular HTTP PUT request returning a 404 error for a valid URL on a JSON server!

After trying to implement Angular HTTP put using reactive forms for the first time, I encountered an issue. Whenever I use the code provided, I receive a 404 error. The error specifically points to a server URL that cannot be found (XHR PUT http://localhos ...

Tips on preventing the initial undefined subscription in JavaScript when using RxJS

I am having trouble subscribing to an object that I receive from the server. The code initially returns nothing. Here is the subscription code: ngOnInit() { this.dataService.getEvents() .subscribe( (events) => { this.events = events; ...

The properties naturalWidth and naturalHeight are both returning a value of zero

There is a code in place to check the ratio of images, which usually works well but occasionally fails when img.naturalWidth and img.naturalHeight return 0. Although this could be due to the image not being fully loaded at that moment, it's puzzling w ...

Tips for converting a JSON object to TypeScript compliant format:

I'm looking to convert a JSON response from: [ { "value": { "name": "Actions", "visible": true, "property": "actions" } }, { ...

Looping through GET requests

I have a Next.js and TypeScript application where a request is made to a webhook integration that returns a Google sheet in JSON format. I've noticed that the integration keeps getting called repeatedly in a loop. Here is a snippet of my code: import ...

Issue with installation of Npm package dependencies

I recently created an npm package from a forked repository at https://github.com/pwalczak83/angular2-datatable After changing only the name and version in the package.json file, I installed the package using npm i -S angular2-datatable-custom. However, up ...

Error TS2339: Cannot access attribute 'reactive_support' on interface 'LocalizedStringsMethods'

Encountering the error TS2339: Property 'reactive_support' does not exist on type 'LocalizedStringsMethods' I recently updated TypeScript from version 2.6 to 2.9, and attempted import LocalizedStrings from 'react-localization&apo ...

Ways to retrieve a Class Level Variable within the onCellValueChanged function in agGrid

Exploring Angular with Typescript for the first time. I'm trying to access Class Level Variables within the onCellValueChanged event of agGrid, but encountering the following error: Cannot read property 'updateDict' of undefined Here&apo ...

The specified property 'slug' is not found within the designated type 'ParsedUrlQuery | undefined'

I am faced with an issue in my code where I am attempting to retrieve the path of my page within the getServerSideProps function. However, I have encountered a problem as the type of params is currently an object. How can I convert this object into a stri ...

Error in Typescript: Cannot assign type 'string[]' to type 'string'

I'm currently developing a project using Next.js with Typescript and .tsx files, and I'm utilizing Supabase as my database. While everything is functioning perfectly on localhost, I'm encountering an issue when trying to build the project o ...

Using the function goToPage() within the TabbedHeaderPager component

I am currently working on a project that involves using TabbedHeaderPager, and I need to change tabs programmatically. I have been attempting to use the function goToPage() but have run into difficulties accessing it. I have tried passing it as a prop an ...

In the latest version of Expo SDK 37, the update to [email protected] has caused a malfunction in the onShouldStartLoadWithRequest feature when handling unknown deeplinks

After updating to Expo SDK 37, my original code that was previously functioning started encountering issues with <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0e7c6b6f6d7a23606f7a67786b23796b6c78667f79627a">[email prot ...

Guidelines for releasing Node.js microservice client as a stand-alone package within the repository

For my current web application project, I have chosen to implement the client <-> api <-> [microservices] pattern. To challenge myself, I am developing my microservices in Clean Architecture with node.js using Typescript. Although I have alrea ...

Next.js page freezes when Axios request is made causing the tab to become unresponsive

Curious about how to troubleshoot (or where to start) with my current Axios problem. I am working on a Next.js project (12.3) and have an axios interceptor hook that manages all of my internal requests. The interceptor functions properly on every action/pa ...