0

In Typescript I am trying to read an XML file with some javascript code and add the text content to a local variable with the following code:

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);
}
}

I am trying to assign the text within the json file to my private local variable jsonText: this.jsonText = rawFile.responseText; which are both of the type 'string'.

When I try this I get the error:

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

Does somebody know how I can do this within typescript? When I remove this. - the responseText can be defined to the jsonText variable which is within the function readTextFile(file)

Klyner
  • 2,884
  • 4
  • 19
  • 39
  • Possible duplicate of [How does the "this" keyword work?](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) – Joe Clay Jun 07 '17 at 13:28
  • 1
    The problemas is that ``this in line `this.jsonText` refers to `rawFile` since it's called from such class. You should apply the typical `self`technique to keep the reference to your own class. – kazbeel Jun 07 '17 at 13:31

2 Answers2

2

I guess you should hold a reference to class somewhere, like:

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

@Injectable()
export class JsonreaderService {    

private jsonText: string;

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

readTextFile(file)
{
  var self = this;
  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)
      {
        self.jsonText = rawFile.responseText;
      }
    }
  }
  rawFile.send(null);
}
}
Michał Sałaciński
  • 2,166
  • 1
  • 9
  • 10
  • You are right! I didn't know or forgot that the 'this' keyword in javascript is not the same as in typescript, java or C# for example. Thanks! – Klyner Jun 07 '17 at 13:44
2

Use an arrow function to save the scope of this:

readTextFile(file)
{
  let jsonText: string;
  var rawFile = new XMLHttpRequest();
  rawFile.open("GET", file, false);
  rawFile.onreadystatechange = () =>
  {
    if(rawFile.readyState === 4)
    {
      if(rawFile.status === 200 || rawFile.status == 0)
      {
        this.jsonText = rawFile.responseText;
      }
    }
  }
  rawFile.send(null);
}
Nitzan Tomer
  • 120,901
  • 33
  • 273
  • 264