Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

angular - How to Include JS file in ionic 3

Im looking for a way to access a variable from external js file which i included in assets/data folder

below is what i tried

placed test.js in assets/data folder

in test.js added variable testvar = "heloo from external js";

added script tag in src/index.html <script src="assets/data/test.js"></script>

in app.component.ts i added this line after imports;declare var testvar: any;

in constructor added this line to log the value console.log(testvar);

result is error : ERROR ReferenceError: testvar is not defined

so, how can i use my js variable in typescript ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This solution only worked for me

Put the import js in src/index.html header tag, before the build/polyfills.js and build/main.js (they are in body tag);

Example : I created a file src/assets/test.js with a var testvar, imported in src/index.html and then in src/app/app.component.ts declared declare var testvar;.

test.js

var testvar = "Hello from external js";

index.html

...
  <link rel="icon" type="image/x-icon" href="assets/icon/favicon.ico">
  <link rel="manifest" href="manifest.json">
  <meta name="theme-color" content="#4e8ef7">

  <!-- cordova.js required for cordova apps -->
  <script src="cordova.js"></script>
  <script src="assets/js/test.js"></script> //here, not in body
...

app.componet.ts

declare var testvar;

@Component({
   templateUrl: 'app.html'
})
export class MyApp {
  @ViewChild(Nav) nav: Nav;
  constructor(private statusbar : StatusBar,  splashScreen: SplashScreen) {
   alert(testvar);
...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...