2016-08-17 93 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