Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import a shared service that lives outside the app folder in an angular 2 app in typescript using systemjs

I have two angular 2 apps in the following structure:

/app
     /app1
     /app2
     /shared

Inside my angular 2 components (written in typescript), I'm importing several modules (that reside in the same folder) without any issues: import { TestService1 } from './test1.service';

However, when I tried to import something from the shared folder, it was unable to load the required module at runtime (browser). import { TestService2 } from '../shared/test2.service'; The browser says: http://something.something.darkside/app/test2.service 404 (Not Found).

I can use the defaultJSExtensions set to true and that will fix the issue. But I would like to know how to configure systemjs correctly to handle this situation.

systemjs.config.js

(function (global) {

    var ngPackageNames = [ bla, ng2packages... ];

    //ng2 apps
    var ngApps = [
        '/app/app1',
        '/app/app2'
    ];

    var map = {
        '@angular': '/node_modules/@angular',
        'rxjs': '/node_modules/rxjs'
    };

    var packages = {
        'rxjs': { defaultExtension: 'js' }
    };

    //adds package entries for each of the needed ng2 packages
    ngPackageNames.forEach(function (pkgName) {
        packages['@angular/' + pkgName] = System.packageWithIndex
            ? { main: 'index.js', defaultExtension: 'js' }
            : { main: '/bundles/' + pkgName + '.umd.js', defaultExtension: 'js' };
    });

    //adds map entries and package entries for the apps
    ngApps.forEach(function (app) {
        var appName = app.substring(app.lastIndexOf('/') + 1);
        map[appName] = app;
        packages[appName] = { main: appName + '.main.js', defaultExtension: 'js' };
    });

    System.config({ map: map, packages: packages });

})(this);
like image 337
SynBiotik Avatar asked Oct 19 '22 05:10

SynBiotik


1 Answers

Include the folder path to your map object.

var map = {
    'shared' : 'app/shared',
    '@angular': '/node_modules/@angular',
    'rxjs': '/node_modules/rxjs'
};

Add in packages add

var packages = {
    'rxjs': { defaultExtension: 'js' },
    'shared': { defaultExtension: 'js' }
};
like image 140
Mwaa Joseph Avatar answered Nov 15 '22 05:11

Mwaa Joseph