2016-08-17 109 views
2

我在离子2中创建一个android应用程序。我在index.html中的脚本标记中声明了一个变量。这个常数值我想在离子2页和提供者代码中使用。我粘贴下面的代码。在此先感谢...ionic 2如何在index.html中使用常量变量的声明?

的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'. -->         
      } 
     } 
+0

正确的做法是[this one](http://stackoverflow.com/questions/38937503/where-to-save-settings-like-api-url-in-ionic2-app/38940262# 38940262)。 – sebaferreras

回答

0

即使有更好的方式在离子应用程序处理静态设置会是this post中的一个,你可以使你的代码工作:

  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> 
    

然后在你的代码:

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

话虽这么说,我还是建议this approach任何离子2应用程序处理静态设置时。

+1

感谢回复@sebaferreras !!我用第二批...并且它工作.. – Shriniwas