Injecting JavaScript page level variable into an integrated Angular2 RC 1 application

To keep this brief, the issue I'm facing is an extension of a Stack Overflow question regarding passing page-level variables into an Angular 2 app service.

Following Gunter's advice from the provided SO question, I attempted to pass a JavaScript variable from the "page level" into my Angular 2 app service. While it works flawlessly in development, bundling the app causes it to fail. I use gulp-jspm-build for bundling with mangle set to false to prevent other errors.

My Angular app resides within a CMS that preprocesses the index.html and replaces specific tokens with values.

The index.html snippet below undergoes token replacement:

<!-- Capture values to pass to app -->
<script type="text/javascript">
    var moduleId = parseInt("[ModuleContext:ModuleId]");
    var portalId = parseInt("[ModuleContext:PortalId]");
    var tabId = parseInt("[ModuleContext:TabId]");
    var dnnSF = $.ServicesFramework(moduleId);
    if ("[ModuleContext:EditMode]" === 'True') {
        var editMode = true;
    }
    // console.log('editMode = ' + editMode);
</script>

<!-- Replace with actual path to system.config.js -->
[Javascript:{path: "~/my-app/systemjs.config.js"}]

<!-- APP selector where it is rendered-->
<my-app>Loading...</my-app>

Note the [ModuleContext:ModuleId] placeholder gets replaced with a necessary numeric value used by the bootstrapped Angular app on the page.

In my main.ts file, I have:

import {bootstrap} from '@angular/platform-browser-dynamic';
import {provide} from '@angular/core';
import {AppComponent} from './app.component';
import {dnnModId, dnnSF, dnnPortalId} from './shared/dnn/app.token';
import {HashLocationStrategy, LocationStrategy} from '@angular/common';
import {ROUTER_PROVIDERS} from '@angular/router';
import {HTTP_PROVIDERS} from '@angular/http';

// declare 
declare var $: any;
declare var moduleId: any;
declare var portalId: any;

// Providers & services should be available app-wide
bootstrap(AppComponent, [
    ROUTER_PROVIDERS,
    HTTP_PROVIDERS,
    provide(LocationStrategy, { useClass: HashLocationStrategy }),
    provide(dnnModId, { useValue: moduleId }),
    provide(dnnPortalId, { useValue: portalId }),
    provide(dnnSF, { useValue: $.ServicesFramework(moduleId) })
]);

I added declare var moduleId: any; to avoid compilation errors in TypeScript, but it gets lost during bundling.

Here's how I define my opaque tokens:

import {OpaqueToken} from '@angular/core';

export let dnnModId: any = new OpaqueToken('moduleId');
export let dnnPortalId: any = new OpaqueToken('portalId');
export let dnnTabId: any = new OpaqueToken('tabId');
export let dnnSF: any = new OpaqueToken('sf');

ERROR ENCOUNTERED

The error occurs at:

core_1.provide(app_token_1.dnnModId, { useValue: moduleId });

In the bundled .js file for the app, the error reads:

app.min.js Uncaught ReferenceError: moduleId is not defined

QUERY:

I need help understanding why this setup functions in development but fails post-bundling.

Thanks ahead of time!

Answer №1

It turned out that my content management system (CMS) was causing the problem. The CMS incorrectly inserted the JavaScript files at the top of the page.

To resolve this issue, I had to modify

[Javascript:{path: "~/my-app/systemjs.config.js"}]

to

<script src="/DesktopModules/regentsigns-app/systemjs.config.js"></script>

The first method is used by the CMS token replacement feature, which placed the bundled angular.min.js file above the necessary selector and inline scripts capturing global variables.

By manually importing the app.js files using a simple script tag, I was able to correct the loading order problem.

Answer №2

Ensure that in your tsconfig.json file, you include the line "module": "commonjs" within the section labeled "compilerOptions"

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

Arranging an array based on numerical values embedded in strings

My array is as follows: var arr = [ '4msterdam', 'Par1s', 'N3w York', '2urich']; Is there a way to sort the elements of this array based on the numbers included in each string? ...

Running a method at any given time within an ngFor loop in Angular 5

On my angular page, I am facing a challenge with updating a variable and displaying it in the HTML within an *ngFor loop. Here is an example of what I need: HTML: <table *ngFor="let data of Dataset"> somehowRunThis(data) <div>{{meth ...

How to filter dependency-injected asynchronous data based on conditions?

I have developed a NodeJS application that utilizes dependency injection. One of the key features of the app is that it can execute multiple functions (modules) simultaneously, and if multiple modules request data from the same async resource, the app ensu ...

Issue occurs when trying to access the 'set' property of an undefined variable, leading to an error message stating "Cannot read property 'set' of undefined" while using 'this

I'm facing an issue while setting up basic cookies for my Vue project. When I try to set a cookie, I encounter the following error. My package.json file indicates that I am using vue-cookies version ^1.7.4. The error message occurs when I click the bu ...

What is the best way to carry out all potential combinations?

Here is a function that generates a random 5-character code like AU330, UEEHB, 2EH8D, HJ1LM. function generateCode(length) { var result = ''; var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; var charactersLength = char ...

Use an array to store nested JSON fields

I'm currently seeking to enhance my proficiency in utilizing JavasScript, React, and Material-UI. I am faced with the challenge of sorting my table using a nested JSON structure and I am encountering difficulties with assigning the JSON fields to my a ...

Is it possible to rewrite this function recursively for a more polished outcome?

The function match assigns a true or false value to an attribute (collapsed) based on the value of a string: function match(children) { var data = $scope.treeData for (var i = 0; i < data.length; i++) { var s = data[i] for (var ...

Experiencing difficulties with exporting data to CSV using MUI DataGrid. How can I ensure that the Excel sheet contains accurate data instead of displaying [Object object]?

Having trouble with exporting to CSV as I am encountering a pesky issue. Instead of the desired value, all I see is [Object object]. Even after implementing the valueGetter method as suggested in the documentation, it does not seem to resolve the problem. ...

React Native TextInput utilizing FieldRenderProps

When working with final-form in React-Native, I encountered an issue while creating a custom TextInput. It seems that specifying the type for FieldRenderProps is resulting in an error: TS2769: No overload matches this call. Overload 1 of 2, '(props: T ...

Create a new object containing a series of function expressions, but exclude the first function parameter

In my current setup, I have a variable called storePattern const storePattern = { state: { }, mutations: { }, actions: {}, modules: { modal: { actions: { openModal(store, name: string): boolean { console.log('Op ...

Having trouble getting Vuejs to work when appending an element to Fullcalender

Hi there, I am facing an issue where appending a custom button to a full calendar event is not working properly with Vue.js methods. It works fine with core JavaScript, but I really want it to work with Vue.js methods. Any ideas on how I can achieve this? ...

Leveraging data from a JSON array

After successfully retrieving a JSON array from PHP using AJAX, I am now faced with the task of utilizing specific values within the array. Although I can currently display the results as a string, my goal is to access and use individual values independen ...

Upon the initial loading of the React component, I am retrieving undefined values that are being passed from the reducer

Upon the initial loading of the React component, I am encountering an issue where the values originating from the reducer are showing up as undefined. Below is a snippet of my code: const [componentState, dispatchComponentState] = useReducer( versionReduc ...

Retrieve the child nodes from the array and organize them into a

Given an array of regions, where the highest region has key: 10 and parent_id: null, the goal is to restructure this array in order to return a tree representation. The desired regions tree structure for input [10] should be: Egypt Zone 1 Tagamo3 Giza H ...

The elusive cookie in NodeJS remained just out of reach

After setting a cookie using the code below: router.get("/addCartToCookie", function(req, res) { let options = { maxAge: 1000 * 60 * 15, httpOnly: true, }; let cartData = { name: "test cookie", slug: slugify(&quo ...

Issue with constructor including an interface

I'm facing an issue with a typescript class that has an interface implemented in the constructor parameter: interface responseObject { a: string; b: boolean; c?: boolean; } class x { a: string; b: boolean; ...

UPDATE: Enhanced Security Measures for Checkout on Bigcommerce - Deselect the pre-selected option "Include shipping address with delivery."

REVISED: I am looking to disable the default option of "I also want to ship to this address" when a customer reaches this stage in the checkout process. I have explored options within BC but haven't found a solution yet. Before resorting to custom co ...

What steps are needed to generate a production version of a TypeScript monorepo application that can be deployed to an Azure Function App?

I've been grappling with understanding Typescript project references and their intended use in a production build, especially for an Azure Function App. I'm not utilizing any monorepo functionality at the package manager level, such as npm worksp ...

The display message in Javascript after replacing a specific string with a variable

I'm currently working on a task that involves extracting numbers from a text input, specifically the first section after splitting it. To test this functionality, I want to display the result using an alert. The text input provided is expected to be ...

Send an identifier to the following page upon selecting a hyperlink in AngularJS

I am currently working on a project that involves displaying a list of places and allowing users to click on a place to view more details on another page. I would like some guidance on how to implement this feature. Here is the HTML code for Page1: <l ...