user2954587 user2954587 - 3 months ago 20
AngularJS Question

angular inject module into multiple modules

I'm loading a module on my base html page called

userFromServer
. I'd like to inject it into both the main app module and also the mixpanel module. However I'm getting an injection error if I try to inject
userFromServer
into
analytics.mixpanel
(angular mixpanel). Is this a circular dependency error or am I missing something? should
userFromServer
be available to all modules? How can I inject
userFromServer
into both modules?

var app = angular.module('App', ['userFromServer', 'analytics.mixpanel'])
// main app with currentUser injectable
var mixp = angular.module('analytics.mixpanel', ['userFromServer'])
mixp.config(['$mixpanelProvider', 'currentUser', function($mixpanelProvider, currentUser) {
// use currentUser here
}]);


userFromServer module

<body ng-app="App" ng-cloak>
<base href="/">

<div class="container">
<div ng-view=""></div>
</div>

<script type="text/javascript">
angular.module('userFromServer', [])
.service('currentUser', function() {
<% if logged_in %>
this.name = '<%= @User.name %>';
this.first_name = '<%= @User.first_name %>';
this.id = '<%= @User.id %>';
this.uuid = '<%= @User.profile.uuid %>';
<% end %>
})
</script>


</body>


the stack trace is:

Failed to instantiate module App due to:

Failed to instantiate module analytics.mixpanel due to:

Unknown provider: currentUser

Answer

This happens because currentUser service instance is injected into config block. Only service providers can be injected here.

Since currentUser is a constant object that doesn't depend on other services and it should be available during config phase, it may be constant service:

angular.module('userFromServer', [])
  .constant('currentUser', {
    <% if logged_in %>
      name: '<%= @User.name %>',
      first_name: '<%= @User.first_name %>',
      id: '<%= @User.id %>',
      uuid: '<%= @User.profile.uuid %>'
    <% end %>
  })