打字稿未定义此。类型

时间:2017-06-12 10:38:36

标签: javascript jquery xml typescript ionic-framework

对于作业,我们需要制作恒温应用程序。我和我的团队希望在离子框架中做到这一点。在一些帮助下,我已经能够获得api.js,我们获得了离子到某种程度的工作。但是现在我遇到了一个我不知道如何解决的错误。

这是新的API.ts:

import * as $ from 'jquery';
//import * as http from '@angular/http';

export class API {
  ServerUrl = '';

  Type = {
    Day: 'day',
    Night: 'night'
  };

  Days = {
    Monday: 'Monday',
    Tuesday: 'Tuesday',
    Wednesday: 'Wednesday',
    Thursday: 'Thursday',
    Friday: 'Friday',
    Saturday: 'Saturday',
    Sunday: 'Sunday'
  };

  MinTemperature = parseFloat('5.0');
  MaxTemperature = parseFloat('30.0');
  MaxSwitches = 5;

  Time;
  CurrentDay;
  DayTemperature;
  NightTemperature;
  CurrentTemperature;
  TargetTemperature;
  ProgramState;

  Program:any = {};

  constructor() {
    this.Program[this.Days.Monday]    = [];
    this.Program[this.Days.Tuesday]   = [];
    this.Program[this.Days.Wednesday] = [];
    this.Program[this.Days.Thursday]  = [];
    this.Program[this.Days.Friday]    = [];
    this.Program[this.Days.Saturday]  = [];
    this.Program[this.Days.Sunday]    = [];
  }

  /* Retrieve day program
   */
  getProgram(day) {
    return this.Program[day];
  }

  /* Sorts the heating periods (the periods when the heating is on) and merges overlapping ones
   */
  sortMergeProgram(day) {
    let program = this.getProgram(day);
    program.sort(function(a, b) {
      return this.parseTime(a[0]) - this.parseTime(b[0])
    });
    for (let i = 0; i < program.length - 1; i++) {
      if (this.parseTime(program[i][1]) >= this.parseTime(program[i + 1][0])) {
        let start = (program[i][0]);
        let end = (this.parseTime(program[i][1]) > this.parseTime(program[i + 1][1])) ? program[i][1] : program[i + 1][1];
        program.splice(i, 2);
        program.push([start, end]);
        this.sortMergeProgram(day);
        break;
      }
    }
  }

  /* Retrieves all data from the server except for weekProgram
   */
  get(attribute_name) {
    return this.requestData(
      "/" + attribute_name,
      function(data) {
        return $(data).text();
      }
    );
  }

  /* Retrieves the week program
   */
  getWeekProgram() {
    return this.requestData(
      '/weekProgram',
      function(data) {
        $(data).find('day').each(function() {
          let day = (<any>$(this)).attr('name');
          this.Program[day] = [];
          $(this).find('switch').each(function() {
            if ((<any>$(this)).attr('state') == 'on') {
              if ((<any>$(this)).attr('type') == this.Type.Day) {
                this.getProgram(day).push([$(this).text(), '00:00']);
              } else {
                this.getProgram(day)[this.getProgram(day).length - 1][1] = $(this).text();
              }
            }
          })
        });
        return this.Program;
      }
    );
  }

  /* Uploads all data to the server except for currentTemperature and weekProgram
   */
  put(attribute_name, xml_tag, value) {
    this.uploadData("/" + attribute_name, "<" + xml_tag + ">" + value + "</" + xml_tag + ">");
  }

  requestData(address, func) {
    let result;
    (<any>$).ajax({
      type: "get",
      url: this.ServerUrl + address,
      dataType: "xml",
      async: false,
      success: function(data) {
        result = func(data);
      }
    });
    return result;
  }

  /* Uploads the week program
   */
  setWeekProgram() {
    let doc = document.implementation.createDocument(null, null, null);
    let program = doc.createElement('week_program');
    program.setAttribute('state', this.ProgramState ? 'on' : 'off');
    for (let key in this.Program) {
      let day = doc.createElement('day');
      day.setAttribute('name', key);

      let daySwitches = [];
      let nightSwitches = [];

      let i, text, sw;
      let periods = this.getProgram(key);
      for (i = 0; i < periods.length; i++) {
        daySwitches.push(periods[i][0]);
        nightSwitches.push(periods[i][1]);
      }

      for (i = 0; i < this.MaxSwitches; i++) {
        sw = doc.createElement('switch');
        sw.setAttribute('type', this.Type.Day);

        if (i < daySwitches.length) {
          sw.setAttribute('state', 'on');
          text = doc.createTextNode(daySwitches[i]);
        } else {
          sw.setAttribute('state', 'off');
          text = doc.createTextNode('00:00');
        }
        sw.appendChild(text);
        day.appendChild(sw);
      }

      for (i = 0; i < this.MaxSwitches; i++) {
        sw = doc.createElement('switch');
        sw.setAttribute('type', this.Type.Night);

        if (i < nightSwitches.length) {
          sw.setAttribute('state', 'on');
          text = doc.createTextNode(nightSwitches[i]);
        } else {
          sw.setAttribute('state', 'off');
          text = doc.createTextNode('00:00');
        }
        sw.appendChild(text);
        day.appendChild(sw);
      }
      program.appendChild(day);
    }
    doc.appendChild(program);
    this.uploadData('/weekProgram', (new XMLSerializer()).serializeToString(doc));
  }

  /* Creates the default week program
   */
  setDefault() {
    let doc = document.implementation.createDocument(null, null, null);
    let program = doc.createElement('week_program');
    program.setAttribute('state', this.ProgramState ? 'on' : 'off');
    for (let key in this.Program) {
      let day = doc.createElement('day');
      day.setAttribute('name', key);

      let daySwitches = [];
      let nightSwitches = [];

      let i, text, sw;

      for (i = 0; i < this.MaxSwitches; i++) {
        sw = doc.createElement('switch');
        sw.setAttribute('type', this.Type.Night);
        sw.setAttribute('state', 'off');
        text = doc.createTextNode('00:00');
        sw.appendChild(text);
        day.appendChild(sw);
      }

      for (i = 0; i < this.MaxSwitches; i++) {
        sw = doc.createElement('switch');
        sw.setAttribute('type', this.Type.Day);
        sw.setAttribute('state', 'off');
        text = doc.createTextNode('00:00');
        sw.appendChild(text);
        day.appendChild(sw);
      }

      program.appendChild(day);
    }
    doc.appendChild(program);
    this.uploadData('/weekProgram', (new XMLSerializer()).serializeToString(doc));
  }

  uploadData(address, xml) {
    (<any>$).ajax({
      type: "put",
      url: this.ServerUrl + address,
      contentType: 'application/xml',
      data: xml,
      async: false
    });
  }

  parseTime(t) {
    return parseFloat(t.substr(0, 2)) + parseFloat(t.substr(3, 2)) / 60;
  }

  /* Adds a heating period for a specific day
   */
  addPeriod(day, start, end) {
    let program = this.getWeekProgram()[day];
    program.push([start, end]);
    this.sortMergeProgram(day);
    this.setWeekProgram();
  }

  /* Removes a heating period from a specific day.
     idx is the idex of the period with values from 0 to 4
  */
  removePeriod(day, idx) {
    let program = this.getWeekProgram()[day];
    let start = program[idx][0];
    let end = program[idx][1];
    program.splice(idx, 1);
    this.setWeekProgram();
  }

  /* Checks whether the temperature is within the range [5.0,30.0]
   */
  inTemperatureBoundaries(temp) {
    temp = parseFloat(temp);
    return (temp >= this.MinTemperature && temp <= this.MaxTemperature);
  }
}

我遇到问题的函数是getWeekProgram(),它正在从提供的服务器中检索weekProgram。但是这个服务器正在发送XML响应(无法获取JSON ......),当行this.Program[day] = []运行时,我收到以下错误:Runtime Error, this.Program[day] is undefined。我不知道如何解决这个错误..我已经尝试删除该行,并尝试将程序变成一个大数组而不是一个对象,但没有任何工作可悲; /。

这是我们正在使用的XML数据:

<week_program state="off">
  <day name="Monday">
    <switch type="night" state="off">00:00</switch>
    <switch type="night" state="off">00:00</switch>
    <switch type="night" state="off">00:00</switch>
    <switch type="night" state="off">00:00</switch>
    <switch type="night" state="off">00:00</switch>
    <switch type="day" state="off">00:00</switch>
    <switch type="day" state="off">00:00</switch>
    <switch type="day" state="off">00:00</switch>
    <switch type="day" state="off">00:00</switch>
    <switch type="day" state="off">00:00</switch>
  </day>
  <day name="Tuesday">
    <switch type="night" state="off">00:00</switch>
    <switch type="night" state="off">00:00</switch>
    <switch type="night" state="off">00:00</switch>
    <switch type="night" state="off">00:00</switch>
    <switch type="night" state="off">00:00</switch>
    <switch type="day" state="off">00:00</switch>
    <switch type="day" state="off">00:00</switch>
    <switch type="day" state="off">00:00</switch>
    <switch type="day" state="off">00:00</switch>
    <switch type="day" state="off">00:00</switch>
  </day>
  <day name="Wednesday">
    <switch type="night" state="off">00:00</switch>
    <switch type="night" state="off">00:00</switch>
    <switch type="night" state="off">00:00</switch>
    <switch type="night" state="off">00:00</switch>
    <switch type="night" state="off">00:00</switch>
    <switch type="day" state="off">00:00</switch>
    <switch type="day" state="off">00:00</switch>
    <switch type="day" state="off">00:00</switch>
    <switch type="day" state="off">00:00</switch>
    <switch type="day" state="off">00:00</switch>
  </day>
  <day name="Thursday">
    <switch type="night" state="off">00:00</switch>
    <switch type="night" state="off">00:00</switch>
    <switch type="night" state="off">00:00</switch>
    <switch type="night" state="off">00:00</switch>
    <switch type="night" state="off">00:00</switch>
    <switch type="day" state="off">00:00</switch>
    <switch type="day" state="off">00:00</switch>
    <switch type="day" state="off">00:00</switch>
    <switch type="day" state="off">00:00</switch>
    <switch type="day" state="off">00:00</switch>
  </day>
  <day name="Friday">
    <switch type="night" state="off">00:00</switch>
    <switch type="night" state="off">00:00</switch>
    <switch type="night" state="off">00:00</switch>
    <switch type="night" state="off">00:00</switch>
    <switch type="night" state="off">00:00</switch>
    <switch type="day" state="off">00:00</switch>
    <switch type="day" state="off">00:00</switch>
    <switch type="day" state="off">00:00</switch>
    <switch type="day" state="off">00:00</switch>
    <switch type="day" state="off">00:00</switch>
  </day>
  <day name="Saturday">
    <switch type="night" state="off">00:00</switch>
    <switch type="night" state="off">00:00</switch>
    <switch type="night" state="off">00:00</switch>
    <switch type="night" state="off">00:00</switch>
    <switch type="night" state="off">00:00</switch>
    <switch type="day" state="off">00:00</switch>
    <switch type="day" state="off">00:00</switch>
    <switch type="day" state="off">00:00</switch>
    <switch type="day" state="off">00:00</switch>
    <switch type="day" state="off">00:00</switch>
  </day>
  <day name="Sunday">
    <switch type="night" state="off">00:00</switch>
    <switch type="night" state="off">00:00</switch>
    <switch type="night" state="off">00:00</switch>
    <switch type="night" state="off">00:00</switch>
    <switch type="night" state="off">00:00</switch>
    <switch type="day" state="off">00:00</switch>
    <switch type="day" state="off">00:00</switch>
    <switch type="day" state="off">00:00</switch>
    <switch type="day" state="off">00:00</switch>
    <switch type="day" state="off">00:00</switch>
  </day>
</week_program>

1 个答案:

答案 0 :(得分:0)

内部函数内的各种this引用不引用类实例。当使用this语法声明函数时,当前function(){...}不会进入函数;为此,您需要使用以下语法:()=>{...}。您可以详细了解this的行为in the TypeScript wiki

但是,在您的情况下,您不希望使用()=>{...}语法,因为您依赖this来引用.each正在处理的项目。因此,您需要在外部手动将类实例this保存在另一个变量中。这些变量的通用名称是self

  getWeekProgram() {
    let self = this;
    return this.requestData(
      '/weekProgram',
      function(data) {
        $(data).find('day').each(function() {
          let day = (<any>$(this)).attr('name');
          self.Program[day] = [];
          $(this).find('switch').each(function() {
            if ((<any>$(this)).attr('state') == 'on') {
              if ((<any>$(this)).attr('type') == self.Type.Day) {
                self.getProgram(day).push([$(this).text(), '00:00']);
              } else {
                self.getProgram(day)[self.getProgram(day).length - 1][1] = $(this).text();
              }
            }
          })
        });
        return self.Program;
      }
    );
  }