简体   繁体   English

如何将外部JavaScript库添加到离子3打字稿项目

[英]How to add an external javascript library to ionic 3 typescript project

for an assignment we need to make a thermostat app. 对于作业,我们需要制作一个恒温应用程序。 I would like to do this in ionic but am struggling with using the provided API right now. 我想在离子中做这个,但我现在正在努力使用提供的API。 We have been provided an API.js file with a set of function that communicate the the server we have to get our data from. 我们已经提供了一个API.js文件,其中包含一组函数,用于与我们从中获取数据的服务器进行通信。 I tried to make these functions myself via a provider but because the server is returning xml data I have not been successful so far. 我试图通过提供程序自己创建这些函数但是因为服务器返回xml数据我到目前为止还没有成功。 So I wanted to use the given API.js by including it in my project but am now struggling to do that as well. 所以我想通过将它包含在我的项目中来使用给定的API.js,但我现在也在努力做到这一点。 So I would like to get some insight on either how to include this external API into my ionic project and use the functions that is has, or on how to use the returned xml data (show it in the app and send altered data back). 因此,我想了解如何将此外部API包含到我的离子项目中并使用已有的函数,或者如何使用返回的xml数据(在应用程序中显示它并将更改后的数据发回)。

Since both files are quite large I've provided some snippets below and full files in pastebin links. 由于这两个文件都很大,我在下面提供了一些片段,并在pastebin链接中提供了完整的文件。

The get and put commands we can use are day, time, currentTemperature, targetTemperature, dayTemperature, nightTemperature, weekProgramState and weekProgram. 我们可以使用的get和put命令是day,time,currentTemperature,targetTemperature,dayTemperature,nightTemperature,weekProgramState和weekProgram。

Thanks a lot in advance!! 非常感谢提前!!

The API.js API.js

var ServerUrl = '';

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

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

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

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

var Program = {};
Program[Days.Monday]    = [];
Program[Days.Tuesday]   = [];
Program[Days.Wednesday] = [];
Program[Days.Thursday]  = [];
Program[Days.Friday]    = [];
Program[Days.Saturday]  = [];
Program[Days.Sunday]    = [];

/* Retrive day program
*/
function getProgram(day) {
    return Program[day];
}

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

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

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

The returned XML data 返回的XML数据

<thermostat><current_day>Thursday</current_day>
<time>23:32</time>
<current_temperature>16.0</current_temperature>
<target_temperature>16.0</target_temperature>
<day_temperature>22.0</day_temperature>
<night_temperature>19.0</night_temperature>
<week_program_state>off</week_program_state>
<week_program state="off">
  <day name="Monday">
    <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="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="on">05:00</switch>
    <switch type="night" state="on">08:00</switch>
    <switch type="day" state="on">12:00</switch>
    <switch type="night" state="on">14:00</switch>
  </day>
  <day name="Tuesday">
    <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>
    <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>
  </day>

What I would do is create a file named API.ts . 我要做的是创建一个名为API.ts的文件。 Inside it I would create an API class containing the properties and functions of API.js , correcting for Typesctipt syntax. 在其中我将创建一个API类,其中包含API.js的属性和函数, API.js校正Typesctipt语法。

It also looks like whoever wrote this file wanted to also use jquery but it isn't imported, so I imported that too. 它看起来像是谁写了这个文件想要也使用jquery但它没有导入,所以我也导入了它。 I suppose you are given this file so make sure you place it inside src/assets and correct the import path in my code in order to have the matching filename. 我想你得到了这个文件所以请确保你把它放在src/assets并更正我的代码中的导入路径以获得匹配的文件名。

So here's what I have for you: 所以这就是我拥有的东西:

import * as $ from '.assets/jquery.js';

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]    = [];
  }

  /* Retrive 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, xml_tag) {
    return this.requestData(
      "/" + attribute_name,
      function(data) {
        return $(data).find(xml_tag).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);
  }
}

Now in any ionic component you want to consume the API, you just import it like so: 现在在您想要使用API​​的任何离子组件中,您只需将其导入:

import { API } from './API'

and then in your code use it like so: 然后在你的代码中使用它如下:

export class yourPage {
  constructor(public api: API){}

  yourFunction() {
    this.api.setDefault();
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在Ionic 2 TypeScript项目中包含外部Javascript库? - How to include external Javascript library in an Ionic 2 TypeScript project? 如何在打字稿项目中导入外部JavaScript库 - How to import an external javascript library in a typescript project 如何将已编译的JavaScript库添加到TypeScript项目? - How to add compiled javascript library to typescript project? 为 Zendfreamework 项目添加外部 javascript 库 - Add external javascript library for Zendfreamework project 如何在打字稿中使用外部javascript库 - Angular 4 - How to use External javascript library in typescript - Angular 4 如何在 Ionic 2 typescript 应用程序上使用没有类型定义的 javascript 库? - How to use a javascript library without type definition on Ionic 2 typescript app? 如何在GWT上添加外部JavaScript库? - How to add external JavaScript Library on GWT? 如何在小部件中添加外部javascript库和样式表? - How to add external javascript library and stylesheets in a widget? 如何在离子项目中为Azure移动应用程序使用JavaScript客户端库? - How to Use the JavaScript Client Library for Azure Mobile Apps in ionic project? 从离子项目中的打字稿调用JavaScript函数 - Call javascript function from typescript in ionic project
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM