Exporting a object in Angular2 Using TypeScript

I've been working on a small Angular2 application using Typescript and things have been going smoothly so far.

My goal is to utilize a file called config that contains all the necessary settings for the application. Here's the file in question:

ConfigObject.js

export var ConfigObject = {
    apiVersion : 'v1/',
    productBox : 'http://localhost:8931/api/'
};

I've been trying to import this file into a service to access some of the settings, but I keep getting an error saying the file cannot be found.

Here's my service:

import { Component, Injectable } from 'angular2/core';
import { Http, Response } from 'angular2/http';
import 'rxjs/add/operator/map';

import { ConfigObject } from '../../ConfigObject';


import { PRODUCTS } from '../data-stores/mock-products';

@Injectable()
export class ProductService {
    constructor(private http: Http) {

    }
    private APIUrl = ConfigObject.apiVersion;
    getHeroes() {
        return Promise.resolve(PRODUCTS);
    }
    getHeroesSlowly() {
        /*return new Promise<Hero[]>(function(resolve) {
            setTimeout(function() {
                return resolve(HEROES);
            }, 2000)
        });*/
        // The below is the new fat arrow version of the above
        /*return new Promise<Hero[]>(resolve =>
            setTimeout(() => resolve(HEROES), 2000)
        );*/
    }
}

The ConfigObject file is located at the root of the application, two folders up. However, when I try to start the application, I receive the following errors in the console:

GET http://localhost:3000/ConfigObject 404 (Not Found)

I'm puzzled as to why this is happening. Any help would be greatly appreciated!

Thanks!

Answer №1

The issue you're facing is connected to the SystemJS setup. The error message you received,

http://localhost:3000/ConfigObject
, indicates that there isn't a proper rule in place to link the module name (../../ConfigObject) with the actual JS file.

A potential solution is to set the defaultExtension to js in your configuration at the root level like so:

System.config({
  defaultExtension: 'js',
  (...)
});

If that doesn't work, you may need to relocate your file to a designated source folder where rules are defined. For instance, you could use the app folder with this configuration:

System.config({
  (...)
  packages: {
    app: {
      defaultExtension: 'js'
    }
  }
});

Refer to the documentation for more detailed information:

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

Is there a way to convert arrow functions in vue files through transpilation?

I have developed a Vue application that needs to function properly in an ES5 browser (specifically iOS 9). One issue I've encountered is that some of the functions within the Vue components are being transformed into Arrow functions: ()=>, which i ...

Is it feasible to connect to an output component without using EventEmitter?

When it comes to creating components, I've found it quite easy to use property binding for inputs with multiple options available like input(). However, when dealing with component outputs, it can be a bit complicated as there's only one option u ...

What is the best way to start the server when the files are located in separate directories?

I have organized my project into two separate folders, one for the client and one for the server Is there a way to use npm start to simultaneously run both the frontend and backend scripts? Check out the screenshot below: View of Two Folders in my Projec ...

Angular implementation for dynamic data fetching in Charts.js

Having an issue with dynamically calling data from my API to populate a Chart.js. Chart.js requires JSON to function properly, and everything works fine when I use local JSON data. However, when trying to use JSON data from the API, I encounter difficultie ...

Inverting the hierarchy of a tree structure

I am currently working with a tree structure and utilizing the jstree jQuery plugin. My main objective is to reverse the structure. https://i.sstatic.net/PG1Ha.png The desired structure should resemble the one shown in this image. I have made modificatio ...

When trying to access a string value for an ID, I encountered an error stating "Element implicitly has an 'any' type because index expression is not of type 'number'.ts(7015)"

Currently, I am working on a project using React and Typescript. My goal is to retrieve a specific string with the key name id from an array of ten objects that contain the id. The screenshot displaying the code produces the desired output in the console; ...

Invoke a different route within Express Router when it needs to display a Not Found error (404)

Hey there, how are you? Below is the code I've been working on: const router = Router(); router.use( `${routePrefix}/v1/associate-auth/`, associateAuthRoutesV1(router) ); router.use( `${routePrefix}/v1/associate/`, JWTVerify, ...

The data-ng-bind directive cannot be used with the <option> tag

Currently, I am in the process of learning angular and encountered a problem that has me stuck. Upon researching on AngularJS : Why ng-bind is better than {{}} in angular?, I found out that both {{}} and ng-bind are said to produce the same result. However ...

What are the steps to code this in Angular14 syntax?

Here's the code snippet: constructor(obj?: any) { this.id = obj && obj.id || null; this.title = obj && obj.title || null; this.description = obj && obj.description || null; this.thumbnailUrl = obj && obj.thumbnailUrl || null; this. ...

Is there a way to customize the language used for the months and days on the DatePicker

Is there a way to change the language of the DatePicker (months and days) in Material UI? I have attempted to implement localization through both the theme and LocalizationProvider, but neither method seems to work. Here are some resources I have looked a ...

The error message states: "An uncaught TypeError has occurred - the object does not possess the 'jqzoom' method."

I am encountering a browser console error while working on a project involving a magento website. Specifically, I need to implement the jqzoom feature on the product view page. Here's what I have done so far: Added jQuery Included the jqzoom librar ...

Error: jQuery function xxxx is not defined

Upon initial launch of the mobile app homepage, an error is encountered. The error message "TypeError: Jqueryxxxxxx is not a function" is displayed, although the API callback results are shown as "jQuery111309512500500950475_1459208158307({"code":1," ...

Obtain a pointer to the timestamp within a embedded Kibana chart on an HTML webpage

The image at the specified link shows a black box labeled @timestamp displaying date and time information. Unfortunately, viewing the image requires a reputation of 10. Link to image: https://www.elastic.co/assets/bltde09cbafb09b7f08/Screen-Shot-2014-09-3 ...

Troubleshooting issues with filtering two MongoDB arrays in ES6 and finding a solution

I have a scenario where I am requesting two arrays of objectIDs from MongoDB, and then attempting to identify the differences between the two arrays. In addition, I am passing these arrays through express middleware using res.locals. Below is the code sn ...

Is it possible to verify the presence of the "#" tag within a string?

As a novice in node.js, I appreciate your patience with my question. We are aware that we can use var regex = /[ !@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/g; regex.test(str); to verify if a string contains special ...

Ways to narrow down const types

For the given scenario, I aim to enforce a specific format [string, number] for all function returns, while allowing varying input arguments for these functions. Access the Playground here type ReturnFormat = [string, number] type Fn = (...args: any[]) =& ...

The equation of jquery plus ie7 results in an undefined value

I am experiencing a strange issue in IE7 with a jQuery script. This problem seems to only occur in IE7. In summary, when I check the console window, it shows that jQuery is not defined - even though I have loaded jQuery (version 1.7.1) from my disk and can ...

The Sanity npm package encounters a type error during the build process

Recently, I encountered an issue with my Next.js blog using next-sanity. After updating all npm packages, I found that running npm run build resulted in a type error within one of the dependencies: ./node_modules/@sanity/types/lib/dts/src/index.d.ts:756:3 ...

Jade console.log() not functioning properly as anticipated

Is it possible that I can just insert -console.log('hello') into any part of the jade code? It doesn't seem to be working, do you know what could be causing this issue? ...

How do I resolve the jQuery error "unable to find function url.indexOf" when working with Vide?

I had previously asked a question regarding the use of the Vide plugin for playing background videos on my website, which can be found here. However, I am now encountering an error that is puzzling me: https://i.stack.imgur.com/UDFuU.png I am unsure abo ...