Sharing a service between multiple Angular Modules

时间:2016-07-11 19:45:06

标签: javascript angularjs

I have a bit of an unorthodox angular set up, and I'm starting to doubt if it's going to work.

I've split the web-app that I'm building into 5 apps. Each will have it's own module, and it's own gulp build that will compile that module into a minified js file that will be included in the html. There will be 1 js build per page.

Then, I have a sharedService module. Each of the other modules will have this sharedService module injected into it. The shared service has it's own gulp build, and is being included in the master template that every other page is inheriting from, so every page will have this shared template js build on it.

I'm finding now though that changes to the sharedService in one app, isn't reflected when I navigate to the other. I'm thinking each app is using it's own version of the sharedService and it's not actually being shared at all, or to be more specific, when navigating to the next app the page refreshes and reloads the services losing the data that existed within them.

I'm using typescript and browserify.

An example of one of my apps:

'use strict';

declare var angular, require:any;

angular.module('compareApp', ['ui.router', 'sharedServices']);

// require module dependencies
require('./compareAppConfig.ts');
require('./compareController.ts');

The shared Service app:

'use strict';

declare var angular, require:any;

angular.module('sharedServices', []);

require('./services/dogService.ts');
require('./services/userService.ts');

And an example of one of the services:

declare var require, angular:any;

angular.module('sharedServices').service('userService', userService);

const API_PATH = "/api/";

function userService($http, $q) {

    var userData = {
        favorites: []
    };

    function getUser(){
        return userData;
    }

    function saveFavorite(dogId){
        userData.favorites.push(dogId);
    }

    return {
        saveFavorite: saveFavorite,
        getFavorite: getFavorite
    };
}

export = userService;

So basically when I save a dog to the favorites array in one app, and then navigate to another app, that array is empty.

1 个答案:

答案 0 :(得分:0)

When you say split the webapp do you mean separate html files?

If you are navigating to an entirely separate page/html file then your code is going to be re-run when the page loads. Therefore any data in your shared service gets wiped.

If you would like to route to different pages of your application while maintaining state I suggest looking into client-side routing using ui-router.