【问题标题】:ionic 2 how to use constants variable's declare in index.html?ionic 2 如何在 index.html 中使用常量变量的声明?
【发布时间】:2016-08-17 13:51:27
【问题描述】:

我在 ionic 2 中创建了一个 android 应用程序。我在 index.html 的脚本标记中声明了一个变量。我想在 ionic 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>

item-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'. -->                                 
          }
        }

【问题讨论】:

标签: javascript angular typescript ionic-framework ionic2


【解决方案1】:

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

  1. &lt;script src="build/js/app.bundle.js"&gt;&lt;/script&gt;&lt;script src="build/js/app.bundle.js"&gt;&lt;/script&gt;之前将脚本包含在变量中。

  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>
    

然后在你的代码中:

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

【讨论】:

  • 感谢@sebaferreras 的回复!我使用了第二种方法......它的工作原理......
猜你喜欢
  • 1970-01-01
  • 2010-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-27
  • 1970-01-01
相关资源
最近更新 更多