如何在其他打字稿中使用打字稿中的函数

How to use functions from typescripts in other typescripts

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

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


}

我想在lightpage.ts中使用setLight()的结果值到home.ts!!

如何导入?

How can I import?

简单。在 home.ts 你将拥有:

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

更多

这是 ES6 导入语法。

您走在正确的轨道上,但您不能在 class (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 ;)