【问题标题】:How to use functions from typescripts in other typescripts如何在其他打字稿中使用打字稿中的函数
【发布时间】:2017-10-27 01:33:04
【问题描述】:

我是打字稿初学者。 我想在其他打字稿中使用打字稿中的函数值。

lightpage.ts

export class LightPage {

//light-on/off
private lightOn: boolean = false;

setLight(): boolean {
    this.lightOn = !this.lightOn;
    var lightResult = this.lightOn;
    console.log("lightResult : " + lightResult);
    return lightResult;
}

home.ts

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { LightPage } from '../light/light';
@Component({

  selector: 'page-home',

  templateUrl: 'home.html'
})

export class HomePage {

    //let lp = new LightPage();


}

我想用setLight()的结果值在lightpage.tshome.ts!!

如何导入?

【问题讨论】:

  • 如果您需要从外部获取类方法而无需先创建对象,您可以简单地构建静态方法

标签: typescript ionic-framework import reference export


【解决方案1】:

您在正确的轨道上,但您不能在类中声明变量 (let)。您应该在构造函数或任何其他函数中使用它。

home.ts

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { LightPage } from '../light/light';
@Component({

  selector: 'page-home',

  templateUrl: 'home.html'
})

export class HomePage {

    //let lp = new LightPage();
    private lp = new LightPage();

    constructor() {
        this.lp.setLight();
    }
}

另外,我会将你的函数 setLight 重命名为 toggleLight ;)

【讨论】:

    【解决方案2】:

    如何导入?

    简单。在home.ts 中,您将拥有:

    import * from {LightPage} from './path/to/lightpage';
    

    更多

    这是 ES6 的导入语法。

    【讨论】:

      猜你喜欢
      • 2016-11-27
      • 2018-01-06
      • 2016-09-18
      • 1970-01-01
      • 1970-01-01
      • 2020-09-30
      • 1970-01-01
      • 1970-01-01
      • 2019-06-21
      相关资源
      最近更新 更多