Struggling to access the "this.array" variable within a TypeScript-powered Angular 4 application

I cannot access the this.array variable in my TypeScript-Angular 4 application.

The error is being thrown at this.services.push because this.services is undefined.

My code looks like this:

export class ServersComponent implements OnInit {
  //Initializing the typescript array
  services: ServerProperties[] = [];
  jQuery.each( array, function( key, value ) {
      //Using this.services to push the data which throws error as this.services undefined.
      //Trying to push the object created
      this.services.push(new ServerProperties(JSON.stringify(value.serviceName), JSON.stringify(value.state),
         JSON.stringify(value.domainName), JSON.stringify(value.releaseVersion),
         JSON.stringify(value.creationDate), JSON.stringify(value.BISERVICEURL), JSON.stringify(value.editionDisplayName)));
  });
}

export class ServerProperties {
  public serviceName: string;
  public state: string;
  public domainName: string;
  public releaseVersion: string;
  public creationDate: string;
  public BIServiceURL: string;
  public editionDisplayName: string;

  constructor(serviceName: string, state: string, domainName: string, releaseVersion: string, creationDate: string,  BIServiceURL: string, editionDisplayName: string) {
    this.serviceName = serviceName;
    this.state = state;
    this.domainName = domainName;
    this.releaseVersion = releaseVersion;
    this.creationDate = creationDate;
    this.ServiceURL = BIServiceURL;
    this.editionDisplayName = editionDisplayName;
  }
}

import { Component, OnInit } from '@angular/core';
import { Injectable } from '@angular/core';
import { Headers, Http, Response } from '@angular/http';
import 'rxjs/Rx';
import { Observable } from 'rxjs/Observable';
import {JQueryStyleEventEmitter} from 'rxjs/observable/FromEventObservable';
import {ServerProperties} from './servers.module';
declare var jQuery: any;


@Component({
  selector: 'app-servers',
  templateUrl: './servers.component.html',
  styleUrls: ['./servers.component.css']
})

@Injectable()
export class ServersComponent implements OnInit {
  allowNewUser= false;
  storeValue: ServerProperties[] = [];
  serverCreationStatus= 'No Server was created! ';
  serverName= '';
  static podServiceName= '';
  static podState= '';
  static podDomainName= '';
  static podReleaseVersion= '';
  static podCreationDate= '';
  static podBIServiceURL= '';
  static podeditionDisplayName= '';
  myJSON= '';
  //declaring server properties array 
  services: ServerProperties[] = [];

  Service_Instances= '';

  total_services= new Array();
  Service_Instances2= '';
  serverCreated= false;
  podPro= {};
  dict= {};

  constructor(private http: Http) {}

  setValues(array){
    jQuery.each( array, ( key, value ) => {
      console.log('Jquery Output 1st' + key + ': ' + value.state );
      console.log('Jquery Output 1st' + key + ': ' + value.serviceName );
      console.log('Jquery Output 1st' + key + ': ' + value.domainName );
      console.log('Jquery Output 1st' + key + ': ' + value.releaseVersion );
      console.log('Jquery Output 1st' + key + ': ' + value.creationDate );
      console.log('Jquery Output 1st' + key + ': ' + value.BI_SERVICE_URL );
      console.log('Jquery Output 1st' + key + ': ' + value.editionDisplayName );
      // this.total_services.push(value.state);
      //  this.total_services.push(value.serviceName);
      //  this.total_services.push(value.domainName);
      //  this.total_services.push(value.releaseVersion);
      //  this.total_services.push(value.creationDate);
      ServersComponent.podState = JSON.stringify(value.state);
      ServersComponent.podServiceName = JSON.stringify(value.serviceName);
      ServersComponent.podDomainName = JSON.stringify(value.domainName);
      ServersComponent.podReleaseVersion = JSON.stringify(value.releaseVersion);
      ServersComponent.podCreationDate = JSON.stringify(value.creationDate);
      ServersComponent.podBIServiceURL = JSON.stringify(value.BI_SERVICE_URL);
      ServersComponent.podeditionDisplayName = JSON.stringify(value.editionDisplayName);
      console.log('Pod State check' + ServersComponent.podState);
      this.services.push(new ServerProperties(JSON.stringify(value.serviceName), JSON.stringify(value.state),
          JSON.stringify(value.domainName), JSON.stringify(value.releaseVersion),
          JSON.stringify(value.creationDate), JSON.stringify(value.BI_SERVICE_URL), JSON.stringify(value.editionDisplayName)));
    });
  }

  ngOnInit() {
  }

  onCreateServer(){
    this.serverCreationStatus = 'Server Instance Created! ' + this.serverName;
    //Trying to get the JSON Response
    return this.http.get('http://127.0.0.1:5000/PodChecker').subscribe( (response: Response) => {
        console.log(response);
        const data = response.json();
        console.log(data);
        this.Service_Instances = data;
        this.dict = data;
        console.log('Data[services]' + JSON.stringify(data['services']));
        console.log(this.dict);
        this.Service_Instances = this.dict['services'];
        //this.setValues(this.dict['services']);
        console.log('Must Check' + JSON.stringify(this.setValues(this.dict['services'])));
        console.log('This Services Output:' + JSON.stringify(this.services ));
      },

      (error) => console.log(error)
    );
  }

  onUpdateServerName(event: Event){
    this.serverName = (<HTMLInputElement>event.target).value;
  }

}

Answer №1

When looping through an array using jQuery.each, you can use arrow function syntax for a more concise code:

jQuery.each( array, ( key, value ) => {

It is recommended to use arrow functions instead of the traditional function keyword because it automatically binds the correct context for this.

For more information on accessing the correct `this` inside a callback function, check out this helpful resource: How to access the correct `this` context inside a callback?

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

Guide to binding input type= 'email' in Knockout.js

My project utilizes KnockoutJS with MVC. I am seeking assistance on determining whether an emailId is valid or invalid. Based on this validation, I need to dynamically enable/disable a button and set an error title for the corresponding textbox. Below is ...

Incorporate dynamic HTML into Angular by adding CSS styling

Just starting out with Angular and have limited front-end experience. I'm feeling a bit lost on how to proceed. Currently, I have a mat-table with a static datasource (will connect to a database in the future), and I need to dynamically change the bac ...

WARNING: Alert raised due to the discovery of two offspring sharing identical keys, `${item}-${index}`

I have been facing the issue of receiving an error message 'ERROR Warning: Encountered two children with the same key, ${item}-${index}' and I am not sure what is causing it. Can someone please guide me on how to resolve this problem? Any help w ...

Using ng-repeat to iterate over an array of strings in Javascript

I am working with a JavaScript Array that contains strings: for(var i =0; i<db.length; i++) console.log(db[i]); When I run the code, the output is as follows: dbName:rf,dbStatus:true dbName:rt,dbStatus:false Now, I am trying to use ng-repeat to ...

What is the best way to retrieve data from multi-dimensional JSON structures?

Looking to extract specific values from my JSON file. console.log( objects.assignments.header.report_type ); I need to display HOMEWORK Javascript $.ajax({ url: "/BIM/rest/report/assignment", type: "POST", dataTyp ...

Stop jquery and/or x-editable from automatically converting strings into objects

I am facing an issue where I want to display a JSON string using x-editable, but it is converting it into an object against my wishes. This results in [object Object] being displayed instead of the actual string. How can I prevent this from happening? var ...

"JQuery encounters a parsing error while trying to process an XML

When I try to make an ajax request for an xml file, I encounter a parse error due to the presence of the xml declaration. Here is my AJAX request: <script> $(document).ready(function(){ $.ajax({ url: "/test/test.xml", ...

Having difficulty interpreting the responseText

Currently experimenting with Redis Webdis Dart Here's my code snippet #import('dart:html'); #import('dart:json'); class ChatClient { XMLHttpRequest listener; int parsePosition = 0; void connect(){ this.listener = ne ...

What is the best way to retrieve data based on a condition using JavaScript within a React application?

I am struggling to load only a specific number of rows that meet a certain condition. Unfortunately, the current code is fetching all 25 rows and the condition is not being applied correctly. If anyone could provide assistance, it would be greatly apprec ...

Utilizing TypeScript to import and export modules under a single namespace

Have a look at this query that's quite similar to mine: https://github.com/Microsoft/TypeScript/issues/4529 Consider the following code snippet: //exported imports export {ISumanOpts, IGlobalSumanObj} from 'suman-types/dts/global'; export ...

Using React JS to iterate over an array and generate a new div for every 3 items

It's a bit challenging for me to articulate my goal effectively. I have a JSON payload that looks like this: { "user": { "id": 4, "username": "3nematix2", "profile_pic": &qu ...

Remove the main project from the list of projects to be linted in

Currently in the process of transitioning my Angular application to NX and have successfully created some libraries. I am now looking to execute the nx affected command, such as nx affected:lint, but it is throwing an error: nx run Keira3:lint Oops! Somet ...

Contrast between sourcing a file from the current directory versus from the node_modules folder

Why does the typescript compiler accept importing from a JS file in the local directory but raises an error when importing from node_modules? Code: import { t2 } from "./t1.js" t2.hello(); import { mat4 } from "./node_modules/gl-matrix/esm ...

What are the steps for changing this JavaScript file into TypeScript?

I'm currently in the process of converting this JavaScript file to TypeScript. However, I've encountered an error with the onClick function as shown below: import React from 'react'; import { Popover } from 'antd'; import A fr ...

Develop a dynamic progress bar using jQuery

I am having trouble creating a percentage bar using jquery and css. The code I have written is not working as expected, particularly the use of jquery css({}). Here is the code snippet: *'width' : width - seems to be causing issues for me / ...

The scroll() function in jQuery does not bubble up

Recently, I encountered an issue with a Wordpress plugin that displays popups on scroll. The code I currently have is as follows: jQuery(window).scroll(function(){ //display popup }); The problem arises with a particular website that has specific CSS ...

When using select2 with AJAX, ensure that the previous response is cleared when the field

Learn how to implement select2 $("#select").select2({ ajax: { url: "/getcity", dataType: 'json', type: 'post', delay: 250, allowClear: false, minimumInputLength: 3, cache: true } }); Every time I focus, ...

develop a submission form using jquery

I am looking to create a submit action where clicking the submit button does not refresh the page. Instead, the data inputted in div1 will be sent to kanjiconverter.php and displayed in div2 using <?php echo $newkanji ?>. There are three forms on thi ...

Ways to access an array's value using a variable in jade

Having trouble understanding why a variable cannot be used to call a value in an array using JS/Jade. This issue arises within a script on a .jade file. The array contains around 400 entries, and one of them is shown below: myFood[10]['Cake'] = ...

What is the best way to ensure the active tab remains visible?

I am using the bs-admin-bcore Bootstrap theme and I am looking to enhance the dynamic functionality of the menu in the "menu.php" file. Here is an example of the current code: <ul id="menu" class="collapse"> <li class="panel"> < ...