离子2如何在index.html中使用常量变量声明?

时间:2016-08-17 13:51:27

标签: javascript angular typescript ionic-framework ionic2

我在离子2中创建了一个Android应用程序。我在index.html中的script标签中声明了一个变量。这个常数值我想在离子2页和提供者代码中使用。我粘贴了下面的代码。提前谢谢......

的index.html

    <html lang="en">
    <head>
      <title>Ionic</title>
      <meta charset="UTF-8">

      <link ios-href="build/css/app.ios.css" rel="stylesheet">
      <link md-href="build/css/app.md.css" rel="stylesheet">
      <link wp-href="build/css/app.wp.css" rel="stylesheet">  
    </head>
    <body>

      <ion-app></ion-app>

      <!-- cordova.js required for cordova apps -->
      <script src="cordova.js"></script>

      <script src="build/js/es6-shim.min.js"></script>
      <!-- Zone.js and Reflect-metadata  -->
      <script src="build/js/Reflect.js"></script>
      <script src="build/js/zone.js"></script>
      <!-- the bundle which is built from the app's source code -->
      <script src="build/js/app.bundle.js"></script>

    <script type=​"text/​javascript">​
       BASE_APP_URL="www.google.com";
    </script>​
    </body>
    </html>

项-details.ts

    import {Component} from '@angular/core';
    import {NavController, NavParams} from 'ionic-angular';
    @Component({
      templateUrl: 'build/pages/item-details/item-details.html'
    })
    export class ItemDetailsPage {
      selectedItem: any;

      constructor(public navCtrl: NavController, navParams: NavParams) {
                this.selectedItem = navParams.get('item');
                console.log(BASE_APP_URL);
         <!---it gives an error that name
          Error TS2304: Cannot find    name 'BASE_APP_URL'. -->                                 
          }
        }

1 个答案:

答案 0 :(得分:0)

即使在this post中使用Ionic应用程序处理静态设置的更好方法,您也可以通过以下方式使代码工作:

  1. <script src="build/js/app.bundle.js"></script> 之前包含变量的脚本,因为这是您要使用它的地方。

  2. 隐式地将该变量声明为window对象的一部分。

    <!-- Your variable -->
    <script type=​"text/​javascript">​
        window.BASE_APP_URL="www.google.com";
    </script>​
    
    <!-- the bundle which is built from the app's source code -->
    <script src="build/js/app.bundle.js"></script>
    
  3. 然后在你的代码中:

    import {Component} from '@angular/core';
    import {NavController, NavParams} from 'ionic-angular';
    @Component({
      templateUrl: 'build/pages/item-details/item-details.html'
    })
    export class ItemDetailsPage {
      selectedItem: any;
    
      constructor(public navCtrl: NavController, navParams: NavParams) {
        this.selectedItem = navParams.get('item');
        console.log(window.BASE_APP_URL);                    
      }
    }
    

    话虽如此,在处理任何Ionic 2应用程序中的静态设置时仍然建议使用this approach