Ionic 从javascript文件调用变量将返回未定义的:离子

jk9hmnmh  于 2022-12-08  发布在  Ionic
关注(0)|答案(2)|浏览(130)

I'm using the Ionic framework and I want to call a variable from a javascript file, but it returns undefined for the variable and prints the console inside the file.

javascript file:

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

typescript file:

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

}

The Result

Hi
Hello from typescript undefined

dgenwo3n

dgenwo3n1#

您应该从JavaScript文件中导出变量,以便在TypeScript文件中访问该值。
因此在"src/assets/js/customers"文件中应该是

export var test = "Hello";

var test = "Hello";
export test;

如果这不是默认导出,则需要导入它,如下所示

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

nue99wik2#

//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
}

相关问题