1

I have a ŧest.json file:

{
  "general": 
          {
            "css": [
              "css/test.css"
            ],
            "js": [
              "js/test.js"
            ]
          }
}

and the following code for my angularjs app:

$stateProvider
            .state('home', {
              url: '/',
              templateUrl: 'views/test.html',
              resolve: {
                loadAssets: ['DynamicService', function (DynamicService) {
                    return DynamicService.get();
                  }]
              }
            })

and here is my service to get file content as js object:

.factory('DynamicService', ['$resource', '$q', '$http',
      function ($resource, $q, $http) {

        var dynService = {};
        var dynUrl = 'api/dynService'; // API to get "ŧest.json" file content

        var error = function (response) {
          // ...
        };

        dynService.get = function () {
          return $http
                  .get(dynUrl)
                  .then(function (response) {
                    return response.data;
                  }, error);
        };

        return dynService;

      }]);

I would like to dynamically load those files css/test.css and js/test.js files, taken after reading the ŧest.json file, before completing router initialization, so that, when visiting /, those files will be injected to DOM.

As you can see, I tried that code in $stateProvider but it does not work.

Any help please? I have angularjs v1.7.0

Thanks

1 Answer 1

1

Actually you are on the right direction, Ui-Router resolve property when gets Promise, it will wait till it resolves and only then will transition to the state ('/').

All you need to do, is to return a promise that waits till all css & js files are loaded. You can achieve that using $q.all that receives array of promises and return a new promise that will resolve whenever all of them will resolve.

Small example:

factory('DynamicService', ['$resource', '$q', '$http',
  function($resource, $q, $http) {

    var dynService = {};
    var dynUrl = 'api/dynService'; // API to get "ŧest.json" file content

    var error = function(response) {
      // ...
    };

    var loadAsset = function(url, type) {
      var defered = $q.defer();
      if (type === 'js') {
        var script = document.createElement('script');
        script.src = url;
        script.onload = defered.resolve;
        script.onerror = defered.reject;
        document.body.appendChild(script);
      } else if (type === 'css') {
        var link = document.createElement('link');
        link.rel = 'stylesheet';
        link.href = url;
        link.onload = defered.resolve;
        link.onerror = defered.reject;
        document.body.appendChild(link);
      }
      return defered.promise;
    }

    var loadAssets = function(assets) {
      // prepare a list of promises & return promise that waits to all.
      var allPromises = ['css', 'js'].reduce((acc, key) => {
        var currentAssets = assets.general[key].map((url) => loadAsset(url, key));
        return acc.concat(currentAssets);
      }, []);

      return $q.all(allPromises);
    }

    dynService.get = function() {
      return $http
        .get(dynUrl)
        .then(function(response) {
          return loadAssets(response.data);
        }, error);
    };

    return dynService;

  }
]);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.