0

I have a service that require external library, for example moment. I import that library as ES6 module. But because AngularJS service defined using closure approach, library is not available when funcA() is being been called.

service.js

import moment from 'moment';
export function DataService() {
    return { 

        funcA: function() {
            return moment().startOf('day').fromNow(); 
        } 
    };
}

controller.js

MyCtrl.$inject = ['$scope', '$state', 'DataService', ...];
export function MyCtrl($scope, $state, DataService, ...) {

    function setInitialDate () {
      ctrl.someDate = DataService.funcA();
    }
}

app.js

import {DataService} from './service.js';
import {MyCtrl} from './controller.js';

var services = angular.module('services', []); 
services.factory('DataService', DataService);

angular.module('mycontrollers').controller('MyCtrl', MyCtrl);

I can import external library into window object, and get access to it inside service using $window. Is there exists other way to get access to library, that was imported as ES6 module, from inside AngularJS service?

3
  • any console errors? Commented Apr 30, 2019 at 19:39
  • What you have looks like it should work. You may need to add more details to your question Commented Apr 30, 2019 at 19:48
  • @NagaSaiA moment is undefined inside funcA(). It is not a message in console, it is the state of moment variable when function is being executed. Commented Apr 30, 2019 at 20:15

1 Answer 1

1

Put the factory and the controller in the same module:

import {DataService} from './service.js';
import {MyCtrl} from './controller.js';

angular.module('app',[])
.factory('DataService', DataService);
.controller('MyCtrl', MyCtrl);
Sign up to request clarification or add additional context in comments.

1 Comment

It works, but during tests I should mock app module. It may be inconvenient if I need to tests only services. Can you suggest the other approach so I could keep modules separated?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.