What is the best way to declare constant variables in index.html for Ionic 2?

I am currently working on developing an Android app using Ionic 2. I have declared a variable in the script tag within my index.html file. This constant value is intended to be used in both Ionic 2 pages and providers code. Below, I have included the snippet of code. Thank you in advance.

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

Answer №1

While it's true that the ideal way to manage static settings in an Ionic app is outlined in this post, there are steps you can take to ensure your code functions properly:

  1. Ensure that the script containing your variable is included before the

    <script src="build/js/app.bundle.js"></script>
    line, as this is where the variable will be utilized.

  2. Implicitly declare the variable as part of the window object.

    <!-- 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>
    

Subsequently, within your code:

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

With all that said, I still advise adopting the recommended approach for managing static settings in any Ionic 2 application.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Shine a spotlight on elements that match with jQuery using live() or on()

Check out my jsFiddle demonstration where I have created a button that adds elements and provides links to delete these elements. Instead of actually deleting the elements in this example, I want to make it so that hovering over the (remove) link, which is ...

Tips on modifying a particular item within a sub-document array using Mongoose?

Working on my node.js and mongoose project, I have a main Schema and a sub-Schema set up. const childrenSchema = new mongoose.Schema({ name: { type: String, required: true, trim: true }, hobbies: [String] }) const parentSchema = new mongoose.Schema({ ...

When using CSS Modules with next aliases, the class names will not be automatically autocompleted if the CSS file is located outside the

When working on a NextJS project using VSCode with the CSS Modules extension and path aliases, I encountered an issue with autocompletion for classNames. While autocompletion works fine for files without path aliases, it does not show up when importing fil ...

ajaxStart event does not trigger when making an Ajax POST request

My ajaxStart event functions properly for ajax loads, but it does not work at all when I do a POST request. The following code is consistently rendered on all pages: $(document).ajaxComplete(function () { hideIcon(); if (stepState !== &a ...

What is the Angular 2 style guide for properties containing a dollar sign?

Discover how parent and children interact through a service with an interesting use of dollar signs in Observable stream names in the official guide over at Angular.io. Take note of missionAnnounced$ and missionConfirmed$ in this code snippet: import { In ...

Is it possible to create a typeguard for a complex combinatory type while retaining the existing type information?

Is there a method to create a TypeScript typeguard for a complex combinatory type that includes multiple "and" and "or" statements to check for the presence of one of the "or" types? For example: interface Type1 { cat: string } interface Type2 { d ...

The presence of a MatFormFieldControl error is necessary within the Mat-form-field, utilizing the *ngIf directive

Having an issue while trying to use *ngIf condition within a <mat-select>. <mat-form-field appearance="legacy"> <mat-label>LOCATION</mat-label> <mat-select *ngIf="exampleObject.innerObject" [(value)]= ...

What is the measure of randomness created by Math.random?

I am trying to create a large random number without the need for cryptographic security. Therefore, I have opted not to use crypto.getRandomValues. Currently, my method of generating the random number is as follows: const random = length => Math. ...

Comparing the construction of web pages with HTML/PHP to the

I am facing an issue with my ajax call where the responseText is returned using a while loop, but the embedded JavaScript is not being loaded. To work around this problem, I have decided to build most of the html on the client side using JavaScript. Coul ...

Matching exact multiple words with special characters using Javascript Regular Expression

My issue involves using RegExp to match multiple words with dynamic values. Whenever a special character like "(" is included, it interprets it as an expression and throws an Uncaught SyntaxError: Invalid regular expression error. let text = 'worki ...

Response coming from an ajax call in the form of a JSON

With the JSON string provided below: {cols:[{"id":"t","label":"Title","type":"string"},{"id":"l","label":"Avg ","type":"string"},{"id":"lb","label":"High","type":"string"},{"id":"lo","label":"Low","type":"string"}],rows:[{"c":[{"v":"Change navigation"},{"v ...

What steps should I take to turn off caching specifically for directory listings?

Is there a way to generate a fresh file list every time without using cached data? I have a basic PHP script that fetches the contents of a directory and stores them in an array. The script works perfectly the first time it is used, but subsequent calls m ...

HTMLMediaElement does not have the setSinkId method

I am currently in the process of developing a WebRTC application using Angular, with the goal of managing audio output through the setSinkId() method within HTMLMediaElement. However, when attempting to use this method, I am encountering an error message s ...

Exploring date formatting in NestJs with Javascript

Currently, I am working with a ScrapeResult mikroOrm entity. I have implemented the code newScrapeResult.date = new Date() to create a new Date object, resulting in the output 2022-07-17T17:07:24.494Z. However, I require the date in the format yyyy-mm-dd ...

The React component is being rendered repeatedly

I am new to React and decided to implement some functionalities to enhance my understanding of the framework. Currently, I am working on a search feature that displays results in a table format. Each row in the table has a delete option, which triggers a p ...

I am encountering difficulties with generating images on canvas within an Angular environment

I am trying to crop a part of a video that is being played after the user clicks on it. However, I am encountering the following error: ERROR DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may no ...

Ways to stop the parent container from causing the child element set as fixed to scroll

When I have a parent and children with the property 'overflow:auto', scrolling the children causes the parent to start scrolling after it reaches the end. How can this be prevented? I do not want the parent container to scroll even after the chi ...

Ways to declare a function within the events onMouseOver and onMouseOut

<div align="right" style="border:1 #FF0 solid; background-color:#999" onMouseOver="javascript: function(){this.style.backgroundColor = '#DDD';}" onMouseOut="javascript: function(){this.style.backgroundColor = '#999';}"> Register & ...

Error Message: Undefined Service in Angular version 1.5.4

I'm currently developing a sample application using AngularJS 1.5.4, built on angular seed, EcmaScript 6, and with a node.js web server. For routing, I am following the guidelines provided here: https://docs.angularjs.org/guide/component-router. Howe ...

Retrieve information from API

When using my API, the data structure returned is as follows: {"msg":"List of all sales", "sales":[{"id":1,"user_id":3,"client_id":3,"description":"test","type":"test","status":"test","sale_date":"2020-04-01","payment_date":"2020-04-15","payment_ref":"tes ...