AngularJS Providers and manual bootstrap

时间:2018-07-24 10:19:09

标签: angularjs angular-providers

I'm having issues in manual bootstrapping an AngularJS application. This app starts in a pop-up window, and I want to hide the real path of the window, so I'm using history.push. Anyway, I need to preserve the original context path, because I need it in app.config, so I try to read it in a JSON file on the server, and store it in a provider. This is the code I'm using to bootstrap the application:

'use strict';
(function () {
  require('./myapp.module.js');
  var myApp = angular.module('app', ['myApp']);

  fetchData().then(bootstrapApplication);

  function fetchData () {
    var initInjector = angular.injector(['ng']);
    var $http = initInjector.get('$http');

    return $http.get('../../config.json?q=' + Date.now()).then(function (response) {
      console.log(response.data);
      myApp.constant('env', response.data); //IT WORKS IN CONTROLLERS
      myApp.provider('contextProvider', function () {
        this.$get = function () {
          function getContext () {
            return response.data.context;
          }

          return {
            getContext: getContext
          };
        };
      });
    }, function (errorResponse) {
      console.log(errorResponse);
    });
  }

  function bootstrapApplication () {
    history.pushState({
      id: 'myApp'
    }, 'My App', window.location.origin + '/myApp');
    angular.element(document).ready(function () {
      angular.bootstrap(document, ['app'], {
        strictDi: true
      });
    });
  }
}());

When I try to use contextProvider in the app.config:

AppConfig.$inject = ['$mdThemingProvider', '$mdIconProvider', '$mdDateLocaleProvider', '$qProvider', 'contextProvider'];

/* @ngInject */
function AppConfig ($mdThemingProvider, $mdIconProvider, $mdDateLocaleProvider, $qProvider, contextProvider) {...}

This is what I get:

Uncaught Error: [$injector:modulerr] Failed to instantiate module app due to:
Error: [$injector:modulerr] Failed to instantiate module myApp due to:
Error: [$injector:unpr] Unknown provider: contextProvider

config is called in the module definition file (it worked properly before I tried to add contextProvider)

How can I fix it?

0 个答案:

没有答案