简体   繁体   中英

Exporting an object literal in Angular2 with Typescript

I am building a small Angular2 application using Typescript and so far so good.

I am wanting to use a file called config which will include all the settings and similar for the application. Here is the file in quetion:

ConfigObject.js

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

I am trying to import this into a service in order to use some of the settings but it is saying the file cannot be found.

Here is 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 sits in the root of the application, 2 folders up. When I try and start the application I get the following errors in console:

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

I am not sure why this is happening?

Thanks!

The problem is related to your SystemJS configuration. Since you have the error: http://localhost:3000/ConfigObject this means that there is no rule to correctly link the module name ( ../../ConfigObject ) with the actual JS file.

You could try to define the defaultExtension to js in your configuration at the root level:

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

Otherwise you need to move your file into a source folder where you define rules on. For example the app one with the following configuration:

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

See this documentation for more details:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM