Storing a string in a variable within Typescript

Attempting to read an XML file in Typescript using some JavaScript code, with the goal of adding the text content to a local variable. The code snippet is as follows:

import { Injectable } from '@angular/core';

@Injectable()
export class JsonreaderService {    

private jsonText: string;

constructor() {
  this.readTextFile("../../assets/content.json");
}

readTextFile(file)
{
  let jsonText: string;
  var rawFile = new XMLHttpRequest();
  rawFile.open("GET", file, false);
  rawFile.onreadystatechange = function ()
  {
    if(rawFile.readyState === 4)
    {
      if(rawFile.status === 200 || rawFile.status == 0)
      {
        this.jsonText = rawFile.responseText;
      }
    }
  }
  rawFile.send(null);
}
}

Effort to assign text from the JSON file to private local variable jsonText - both being of type 'string':

this.jsonText = rawFile.responseText;

Encountering an error when trying:

Property 'jsonText' does not exist on type 'XMLHttpRequest'

Would appreciate any insight on executing this task in TypeScript. Omitting this. allows for defining responseText to the jsonText variable within the function readTextFile(file).

Answer №1

One possible solution could be to store a reference to the class in a variable like this:

import { Injectable } from '@angular/core';

@Injectable()
export class JsonReaderService {

private jsonText: string;

constructor() {
  this.loadJsonFile("../../assets/data.json");
}

loadJsonFile(file) {
  var self = this;
  let jsonText: string;
  var request = new XMLHttpRequest();
  request.open("GET", file, false);
  request.onreadystatechange = function () {
    if(request.readyState === 4) {
      if(request.status === 200 || request.status == 0) {
        self.jsonText = request.responseText;
      }
    }
  }
  request.send(null);
}
}

Answer №2

Utilize an arrow function for preserving the context of this:

retrieveFileData(file)
{
  let jsonData: string;
  var fileRequest = new XMLHttpRequest();
  fileRequest.open("GET", file, false);
  fileRequest.onreadystatechange = () =>
  {
    if(fileRequest.readyState === 4)
    {
      if(fileRequest.status === 200 || fileRequest.status == 0)
      {
        this.jsonData = fileRequest.responseText;
      }
    }
  }
  fileRequest.send(null);
}

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

Manipulate image position with touchmove event using CSS3 transformations on an iPad

Looking to adjust the position of an image on my iPad3, but running into some difficulties. The movement isn't as smooth as desired and seems to lag behind the gestures being made. This is what I have so far (a 3MB base64 image) <img src="data:i ...

How can I ensure that my script reruns when the window is resized?

Clearly, the question is quite straightforward... I have a script that is drawing graphics across the window. Currently, when I resize the window (e.g., make it full screen), the script only responds to the original size of the window. It should refresh a ...

What is the best way to create a universal limitation for a larger collection of a discriminated union?

Is it possible to enforce that when defining a generic class Foo<X>, where X represents a discriminated union type, X must be a superset of another discriminated union Y? In my specific scenario, I am utilizing a discriminated union to differentiate ...

The function did not execute properly, resulting in the express route returning no value

Encountering some issues with Express routes that are behaving inconsistently despite having identical code execution. The goal is to have a client application make API calls like this: async search(){ const query = this.$refs.searchInput.value; ...

What could be causing the NoScript tag to malfunction across different web browsers?

I've incorporated the NoScript tag into my JSP pages in the head section. To avoid conflicts with tiles, I made sure not to include multiple NoScript tags. However, I am experiencing issues in Internet Explorer where it doesn't seem to be working ...

Using Typescript to test with Karma, we can inject a service for our

I'm currently experiencing a problem with running tests in my application. I recently transitioned to using TypeScript and am still in the learning process. The specific error I'm encountering is: Error: [$injector:unpr] Unknown provider: movie ...

Looking to conceal an <hr> element using jQuery's slideToggle function and then reveal it when clicked once more

I recently embarked on my journey to learn jQuery. I encountered a challenge with a simple button that triggers the slideToggle function to show/hide a div. Directly above this toggled div, there is an break line which I want to hide when the button is in ...

Strategies for bypassing Jquery form validation within a single form element

I want to implement form validation for all form elements, but I need to exempt one if a specific checkbox is checked. HTML <form id="reg_form"> <div class="control-group"> <div class="control"& ...

Using a React PureComponent to pass parameters from a Child component

I am facing an issue with my TodosList component that displays a list of individual Todo components. Below is the code snippet for the Todo component: export class Todo extends React.PureComponent { render() { return ( <li onClick={this.pr ...

How can you loop through keys and values in a JSON object using JavaScript?

I am attempting to cycle through the JSON data below: { "VERSION" : "2006-10-27.a", "JOBNAME" : "EXEC_", "JOBHOST" : "Test", "LSFQUEUE" : "45", "LSFLIMIT" : "2006-10-27", "NEWUSER" : "3", "NEWGROUP" : "2", "NEWMODUS" : "640" } The keys in this JSON are d ...

Can someone explain the variance between these two script codes? Are they entirely distinct, or can I utilize just one source?

<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> It appears that one script is for jQuery and the ...

Angular directive for resizing C3 charts

I've recently implemented a basic donut chart using C3, which I've enclosed in a directive and everything is functioning smoothly. Below is the code for my directive: angular.module('dashboardApp').directive('donutChart', fu ...

acquiring the main class instance within a function without relying on an arrow function

Within my Angular project, I have integrated a datatable with row grouping and row callbacks. Datatable Options openPositionDatatableOptions = { sDom: 'rt<"bottom"p>', ajax: (data, callback, settings) => { this.service.ge ...

utilize jQuery and AngularJS to transform a JSON object into a nested JSON structure

Is there a way to convert my current JSON file into a nested JSON structure like the one below? I've attempted various methods (How to convert form input fields to nested JSON structure using jQuery), but I'm not achieving the desired outcome. Ca ...

Using both ng-if and ng-click in AngularJS for enhanced functionalities

There's a button that should display a toggle only when the value is greater than 0; otherwise, it shouldn't do anything. This snippet of code shows how things were prior to adding ng-if: <span >{{values.valuesNumber}} <i class= ...

I'm curious, is there a method to add animation to dynamically adjust the size of the header within the HeaderFooterLayout

Looking for a way to animate the header size within a HeaderFooterLayout? I have been attempting to resize it with an animation, but it seems like there is no specific API for this. Are there any techniques or workarounds that can be used to achieve this ...

Exploring elementary Expressjs query concepts

Just getting started with nodejs and feeling a bit confused. I have a form on my website where users can submit information, and I want to display a response message in an HTML element once the form is submitted. I've been using body parser and Jade v ...

Implementing a restricted Mongoose promise loop iteration count

Currently, I am developing an online store using Node, Express, and Mongoose. In the postCheckout Controller, which is responsible for handling user purchases, I am facing an issue. When a user buys a product with a quantity of 5, the code should check i ...

Observing the state of a variable within a directive using a service from a different module

I currently have two modules named "core" and "ui". The "ui" module has a dependency on the "core" module. Below is the code for my core.js file: var core = angular.module('core', [ 'ngRoute' ]); // Services core.service('httpI ...

I am looking to modify the appearance of specific sections of a searched word in React.js, such as making them bold or lighter. Can anyone

After coming across several similar questions, I realized none quite matched my issue. Specifically, I am attempting to style only the part of the search result that relates to the entered query. For instance, if the query is "Thi", I want the result to di ...