从javascript文件调用变量会返回一个未定义的:Ionic



我使用的是Ionic框架,我想从javascript文件中调用一个变量,但它为变量返回undefined,并在文件中打印控制台。

javascript文件:

console.log('Hi!')
var test = "Hello";

打字脚本文件:

import * as testfile from "src/assets/js/customers"
export class CustomersPage implements OnInit {
test:any='j';
constructor (){
this.test= testfile.test;
console.log('Hello from typescript', this.test);
}
}

结果

你好,来自typescript未定义的

您应该从JavaScript文件中导出变量,以便在TypeScript文件中访问该值。

所以在你的"src/assets/js/customers"文件中应该是

export var test = "Hello";

var test = "Hello";
export test;

如果这不是默认导出,你需要像一样导入它

import * as { testfile } from "src/assets/js/customers"

//Dont forget to export your JS file to use in other files.
import * as testfile from "src/assets/js/customers"
export class CustomersPage implements OnInit {

constructor (
public test: testfile.test
){}
async ngOnInit(){
console.log('Hello from typescript', test);
}
}
//or
import * as testfile from "src/assets/js/customers"
export class CustomersPage implements OnInit {

async ngOnInit(){
this.test = testfile.test
console.log('Hello from typescript', this.test);
}

test
}

相关内容

最新更新