Issues encountered while executing multiple http.get requests - Angular throws an error message stating "Cannot read property 'get' of undefined"

This project I've been working on involves receiving real-time data from an API. The data is sourced from the API and I collect variables by utilizing a .CSV file stored on the web server of a S7-1500 Siemens.

In order to continuously receive real-time data, I aim to set up a setInterval in my service to execute this function multiple times.

Initially, during the first loop, the API call functions as expected. However, upon subsequent loops, an error arises:

Type Error: Cannot read 'get' of undefined 
at line.service.ts 
at Array.map(<anonymous>) 
at getData(line.service.ts:25).

The issue seems to revolve around http.get during the second iteration, but I've struggled to find a resolution after extensive searches.

Below is the code:

import {BehaviorSubject, combineLatest, Subject, Subscription} from 'rxjs';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import {Injectable, OnDestroy} from '@angular/core';

@Injectable()
export class LineService{
  constructor(private http: HttpClient) {
    this.getData();
    setInterval(this.getData, 5000);
  }

  lineSubject = new BehaviorSubject<RcvData[]>([]);

  getData(): void {
    // Function content goes here...
  }
}


class RcvData{
  // Class definition goes here...
}

I would greatly appreciate any insights or solutions to this problem. Thank you!

Answer №1

There are several issues that need to be addressed in this code snippet

  1. The use of `setInterval` with a callback function creates a problem as the `this` keyword inside the callback refers to itself rather than the enclosing class.

  2. Using `setInterval` for regular polling of endpoints may result in multiple open subscriptions leading to potential memory leaks.

  3. `combineLatest` is more suitable for data streams rather than one-off observables like Angular HTTP calls. Consider using `forkJoin` instead.

Here's a better approach:

  1. Utilize RxJS `timer` function to emit notifications at regular intervals.
  2. Implement a higher order mapping operator such as `switchMap` to transition from the notification emitted by `timer` to the HTTP request.
import {timer, BehaviorSubject, combineLatest, Subject, Subscription} from 'rxjs';

@Injectable()
export class LineService {
  constructor(private http: HttpClient) {
    this.getData();
  }

  lineSubject = new BehaviorSubject<RcvData[]>([]);

  getData(): void {
    const lists: string[] = [
      'assets/donnee-l1.csv',
      'assets/donnee-l2.csv',
      'assets/donnee-l3.csv',
      'assets/donnee-l4.csv',
      'assets/donnee-l5.csv',
      'https://192.168.0.2/DataLogs?Path=/DataLogs/MyDataLog7.csv&Action=DOWNLOAD&E=1'
    ];
    const reqs$ = lists.map(list => this.http.get(list, {responseType: 'text'}));

    timer(0, 5000).pipe(
      switchMap(_ => forkJoin(reqs$))
    ).subscribe({
      next: (listResults) => {
        console.log(listResults);
        const parsedListResults = listResults.map(data => {
          const csvToRowArray = data.split('\n');
          const lastRow = csvToRowArray[csvToRowArray.length - 2];
          const row = lastRow.split(',');
          return new RcvData(
            parseInt(row[0], 10),
            row[1], row[2],parseInt(row[3], 10), row[4], row[5], row[6], row[7],
            parseInt(row[8], 10),
            parseInt(row[9], 10),
            parseInt(row[10], 10),
            parseInt(row[11], 10),
            parseFloat(row[12]),
            parseFloat(row[13]),
            parseFloat(row[14]),
            parseFloat(row[15]),
            parseFloat(row[16]),
            parseInt(row[17], 10))
        });
        this.lineSubject.next(parsedListResults);
        console.log(this.lineSubject);
      },
      error: (error) => {
        // handle error
      }
    });
  }
}

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

Retrieving the selected element from every division of a stack bar graph with multiple sections in Chart.js

I have created a stacked bar chart with three different sections or data sources. I am trying to figure out how to determine which section a user has clicked on. Here is the code from my .ts file: this.chart = new Chart("Chart1", { type: 'bar&ap ...

Struggling to share information between components using RxJS Subject or a shared service?

I've been attempting to transfer data between components using a Subject and a shared service, but I'm encountering issues with it not functioning as expected. It's worth mentioning that I included the service at the module level rather tha ...

The error message "Property not found on type 'Product | Customer' in React Typescript" is indicating that the specified property does not exist on the

I am currently working on a React app using TypeScript where I need to manage data for Customers and Products. To enhance this functionality, I plan to create a form component that can be used for updating either a Customer or a Product. The idea is to pr ...

Creating dynamic components from JSON elements does not trigger a rerender of components within an array

Imagine having a simplified input structure like this: [ { type: "text", text: "how are you {name}" }, { type: "input", input: "name" }, { type: "text", text: "good to ...

The expect.objectContaining() function in Jest does not work properly when used in expect.toHaveBeenCalled()

Currently, I am working on writing a test to validate code that interacts with AWS DynamoDB using aws-sdk. Despite following a similar scenario outlined in the official documentation (https://jestjs.io/docs/en/expect#expectobjectcontainingobject), my asser ...

Identity Pool ID is not being recognized by AWS Cognito when integrated with Angular

Currently working with Angular 4, and in the process of authenticating a specific user after receiving the SAML response from the IdP, encountering a '400 Identity Pool ID not found' error from AWS. After confirming that the ID matches what is d ...

Using *ngFor to display the initial element from an array

Here is the code I am currently using: <div *ngIf="gamedata.notOver" class="columns"> <div class="column has-text-centered" *ngFor="let board of boards; let i = index"> <table class="is-bordered" [styl ...

Selecting a value in Angular using the change method

Currently, I have a select component along with a function in place to retrieve the value selected from the dropdown. The issue lies in the fact that the value returned is undefined. It was functioning properly when I was utilizing Angular Material, but t ...

What is the best way for me to generate a fresh object?

In one of my components, I have implemented a feature where clicking on an image toggles a boolean variable to show or hide a menu. The HTML structure for this functionality is as follows: <img src="../../assets/image/dropdown.png" class="dropdown-imag ...

What is the process for configuring vue.config.js with typescript?

Just starting out with typescript and running into an issue while configuring vue.config.js const webpack = require("webpack"); module.exports = { plugins: [ new webpack.DefinePlugin({ __VUE_I18N_FULL_INSTALL__: true, __ ...

Angular: Connecting template data to different visual presentations

Looking for a solution to display data and map values to another presentation without needing complex ngIf statements or creating multiple components. Check out this sample: https://stackblitz.com/edit/angular-9l1vff The 'vals' variable contain ...

Using @ViewChildren in Angular 2 for creating recursive components

I am working on a recursive component that showcases tag A. Firstly, there is the parent component - HTML <div class=" suggestions" style="display : inline-block;" tabindex=-1 #autocompleteDiv> <span style="width: auto;cursor: pointer;posit ...

Can variable values be utilized as a union type within Typescript?

I'm attempting to achieve a setup similar to the following example using Typescript: const fruitApple:string = 'Apple'; const fruitOrange:string = 'Orange'; export type FruitOptions = fruitApple | fruitOrange //the compiler doe ...

A one-to-many relationship does not include the insertion of the parent item

My database has a one to many relationship. When I perform a select operation, everything works correctly. However, when trying to insert data, the insertion occurs in the main table, but updates are triggered in other tables. Error Log from Console [0] ...

"Prior to authenticating the user, the Angular route guard is triggered

A route guard was successfully implemented to redirect users to the login page if they are not authenticated, with the login check being of type Observable. Everything works fine when a user is logged in and navigates to a protected page: { path: 'pr ...

The data type 'Observable<Object>' cannot be assigned to the data type 'Observable<Product>'

I am facing an issue with my service: Type Observable 'Object' is not assignable to type Observable 'Product'. Do you have any suggestions on how to resolve this problem? Here is a snippet of my code: export class Product{ public id:n ...

Following the transition to Angular 17 and the conversion to a standalone loader interceptor, both the component and its functionality are failing to work as expected

Our project is built in Angular Version 17. We have implemented a loading functionality using the loading.component.ts and loader.service.ts files, which are bound in app.component.html and progress.interceptor.ts as shown in the code snippet below. The lo ...

Retrieving live radio-button data in Angular 2

I am having trouble getting dynamic answers to populate my questions effectively. Although everything is functioning correctly, I am struggling to understand how to retrieve the value of a dynamic radio button with a question presented in this format: Ge ...

Encountered build problems after transferring Ionic2 app from Mac to PC

After transferring my ionic2 application from a Mac to a Windows PC along with the nodemodules, I attempted to run it using npm run android. However, an error appeared as detailed below: https://i.sstatic.net/K1LS0.png My current Ionic information is as ...

Using the scrollIntoView method on an element with a height of 0 within an Angular 2+ application

I am currently working with the following HTML code snippet: <div class="row-20 st-margin" *ngIf="role == 'Administrator'" id="hr-data"> <div class="col-md-12"></div> </div> After ...