Steps for creating an empty array in a TypeScript function and dynamically adding objects to it with each function call

As I work with TypeScript and Angular, my goal is to establish an empty array in the testConnection function that can accommodate the addition of objects each time the function is triggered, without wiping out the existing contents of the array.

This is the testConnection function:

testConnection(system) {
    var systemList = [];
    this.service.testConnection(system)
      .subscribe(conn => {
        if (conn == 'Success') {
          this.snackBarHandler.open('Connection Found', 'success');
          system.isClicked = false;
          system.connection = true;
          systemList.push(system);
        }
        else {
          this.snackBarHandler.open('Connection Failed', 'failure');
          system.isClicked = false;
          system.connection = false;
          systemList.push(system);
        }
      }, err => console.log(err));
  }

At present, the system object gets added to the array due to the current logic. However, since the empty array declaration exists within the function itself, it undergoes a reset upon every function call. Despite attempts to declare systemList at the top of the class as (systemList = any[]), referencing it within the function results in undefined output.

Is there a way for me to append system objects to the array whenever the function is executed, while retaining the existing objects in the array?

Answer №1

If you want the list to persist, one approach is to set a component variable outside of the function.

export class SystemComponent implements OnInit {

  constructor(private service: TestConnectionService) {}

  systemList = []

  testConnection(system) {
    this.service.testConnection(system)
      .subscribe(conn => {
        this.systemList.push(system);
        if (conn === 'Success') {
          this.snackBarHandler.open('Connection Found', 'success');
          system.isClicked = false;
          system.connection = true;
        }
        else {
          this.snackBarHandler.open('Connection Failed', 'failure');
          system.isClicked = false;
          system.connection = false;
        }
      }, err => console.log(err));
  }
  ngOnInit(): void {}
}

Another option is to utilize a service to store the state of the system list, especially useful for multiple components accessing it.

interface System {
  some: string
  props: string
}

@Injectable({ providedIn: 'root' })
export class SystemService {
  private _systemList$$ = new BehaviorSubject<System[]>([])


  get systemList(): System[] {
    return this._systemList$$.value
  }

  addToSystemList(system: System) {
    this._systemList$$.next([...this.systemList, system])
  }

  constructor() {}
}

In this case, your testConnection function would interact with the service like so:

testConnection(system) {
  this.service.testConnection(system).subscribe(
    conn => {
      this.systemService.addToSystemList(system)
      if (conn === 'Success') {
        this.snackBarHandler.open('Connection Found', 'success')
        system.isClicked = false
        system.connection = true
      } else {
        this.snackBarHandler.open('Connection Failed', 'failure')
        system.isClicked = false
        system.connection = false
      }
    },
    err => console.log(err)
  )
}

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

Filtering elements using two dropdown lists

In my list, each li element has data-name and data-body attributes. I want to display only the li elements that match the selected values. The first select option is for selecting the car name, while the second select option is for selecting the car body. ...

Managing AJAX Errors in PHPAJAX error handling tips for developers

My current code is only set up to display a general error message when an error occurs during execution. I want to improve it by returning specific error messages for different scenarios. However, I have not been able to find satisfactory solutions in my s ...

array containing if-else statements

Incorporating Google voice recognition into my application has been successful. Now, I am exploring the possibility of initiating actions via voice commands. Below is a snippet of code from my onActivityResult method: @Override protected void onAc ...

Using the .show() function will not alter the outcome or trajectory

I am currently working with some divs in my project where I want to implement the JQuery functions .show() and .hide(). However, I have encountered an issue where I am unable to change the effects or directions of these animations. Here is a snippet of th ...

"Using JavaScript to toggle a radio button and display specific form fields according to the selected

Currently, I am attempting to show specific fields based on the selected radio button, and it seems like I am close to the solution. However, despite my efforts, the functionality is not working as expected and no errors are being displayed. I have define ...

Performing inner joins on 2 tables using Mongoose

My inner join query seems to be resulting in a left join unexpectedly. I have 2 tables with relations and I'm trying to retrieve movies along with their genre names. Here are the models I'm working with: // Movie const MovieSchema = new mongoose ...

Issue with connecting React Router v4 to Redux - dispatch function not being properly passed

Recently, I've been working on migrating my app to React Router v4 and encountered some challenges due to the significant changes in the API. Here's where I currently stand: Setting Up the Router const createStoreWithMiddleware = applyMiddlewar ...

Is it preferable to load JQuery before displaying the content of the HTML page?

My mobile site is set to 762px width, which is ideal for a PC screen. However, I am trying to style it to be 320px wide for an iPhone using JQuery. The issue I am facing is that when the page loads, it initially appears at the larger width and then resizes ...

Maintaining stability in Three.js: How to prevent an object from moving during zoom

In my application, I utilize Three.js for creating a 2D presentation. To achieve this, I set up an Orthographic camera with MapControls. Within the scene, there are various objects that can be panned and zoomed in and out in a 2D space. However, there is o ...

Getting an Object from AngularJS to a Server-Side API: A Step-by-Step Guide

In my VisualStudio, I have an MVC and API WebApplication Project. Utilizing angularjs on the client side, I aim to establish communication between the client and server using angularjs resource to transmit data to my CRUD Api methods. Retrieving and modif ...

using configureStore instead of createStore

After updating my packages, I received a notification from VScode indicating that the createStore function was deprecated. This prompted me to go ahead and replace it with the recommended alternative. In my store file, I left the original line as a commen ...

Error: The function setIsEnabled does not exist

Currently, I am in the process of merging two separate next.js projects to create a website that can utilize the Cardano wallet 'Nami'. The code for accessing the wallet functions correctly in its original project, but when transferred over, it p ...

What is the best method to include a new column in a Pandas dataframe consisting of arrays containing the n-values preceding another column?

I am a beginner when it comes to Python and pandas. I am struggling with finding an elegant solution to the problem at hand. Imagine we have a basic pandas dataframe. import numpy as np import pandas as pd from pandas import DataFrame, Series df = pd.Dat ...

Modify the value of a variable inside another {{variable}} (not sure what it's called)

I am looking to update the variable "prefs" to reflect either "easy, medium, or hard" options based on user interaction. For instance: THIS {{choice.prefs.title}} NEEDS TO BE UPDATED TO {{choice.easy.price}} or {{choice.medium.price}} or {{choice.hard. ...

Fetching database entries upon page load instead of using the keyup function in JavaScript

Here is an HTML form input provided: <input type="text" id="username" value=""> In this scenario, when a username like "John" is entered and the enter button is pressed, the script below retrieves database records: $(function(){ //var socket = ...

Using addThis on Ajax pages may result in Facebook (no title) errors

I have implemented addThis for creating share buttons on a project. The email and Twitter functionalities are working fine, but I am facing issues with Linkedin and Facebook. I understand that they require opengraph to function properly, but what if the co ...

Button click causing TextField to print incorrectly

I am working on implementing a feature in my react application where users can input a search term, and upon pressing the button, it will be used to perform a search. The text input field and button are utilizing material-ui components. At this stage, I si ...

How to selectively disable options in p-dropdown using Angular Reactive Forms

Implementing PrimeNg p-dropdown in a component. <p-dropdown [options]="productRequest" formControlName="request" optionLabel="ProductName" (onChange)="someFunction('request')"> </p-dropdown> ...

Passing Data from $http.get to Angular Controller Using a Shared Variable

One issue I'm facing is the inability to pass the content of a variable inside $http.get() to the outside scope, as it always returns undefined. I attempted using $rootScope, but that approach was not successful. controller('myControl', fu ...

Troubleshooting data binding issues in Angular.js using Jade and Express

I've been diving into AngularJS using Dan Wahlin's tutorial (http://youtu.be/i9MHigUZKEM?t=13m35s). In my views/index.jade file, I've implemented the code below: !!! 5 html(data-ng-app='') head title Angular Tutorial body ...