ui-router: async data in templateUrl function

2019-03-04 05:13发布

问题:

I've run into quite a novel problem with ui router. I'm basically trying to query my API for a template url, which is stored and returned as a Resource object. The problem, is it seems that the templateUrl function is returning as undefined. My code is as follows:

(function() {
    'use strict';

  angular.module('myApp')
    .config(function ($stateProvider, PageProvider, $httpProvider) {
      $stateProvider
        .state('core', {
          abstract: true,
          templateUrl: 'app/core/core.index.html',
          controller: 'CoreController',
          controllerAs: 'vm'
        })
        /* Parent page view */
        .state('core.page', {
          url: '/:slug',
          views: {
            'page_content@core': {
              templateUrl: function(params) {
                var slug = params.slug;
                // only need to load core template
                var url = 'assets/templates/' + slug + '.html';

                return url;
              },
              controller: 'PageController',
              controllerAs: 'vm'
            }
          }
        })
        .state('core.page.child', {
          url: '/:child',
          views: {
            'page_content@core': {
              templateUrl: function($stateParams) {
                PageProvider
                  .$get() // $get() returns Page service
                  .findOne($stateParams.child)
                  .$promise
                  .then(function(data){
                    return data.template.url;
                  });
              }
            }
          }
        });
      });
})();

I set a breakpoint for my state, 'core.page.child', to see what variables were available in the scope, and I found something quite strange:

I really don't understand why this is happening, since .then(cb) is only called AFTER the promise is resolved, which means it should return the correct value as expected - but it doesn't.

Any help would be much appreciated.

Edit: I should add that what is happening is that ui-router is simply not loading my template at all - I get an empty ui-view. I had initially thought it might be a problem with my $stateProvider configuration, but that doesn't seem to be the case.

Edit2: I dug a little into the source code based on the call stack. It seems that both of you are correct - ui-router does NOT work with promises.

/**
 * @ngdoc function
 * @name ui.router.util.$templateFactory#fromConfig
 * @methodOf ui.router.util.$templateFactory
 *
 * @description
 * Creates a template from a configuration object. 
 *
 * @param {object} config Configuration object for which to load a template. 
 * The following properties are search in the specified order, and the first one 
 * that is defined is used to create the template:
 *
 * @param {string|object} config.template html string template or function to 
 * load via {@link ui.router.util.$templateFactory#fromString fromString}.
 * @param {string|object} config.templateUrl url to load or a function returning 
 * the url to load via {@link ui.router.util.$templateFactory#fromUrl fromUrl}.
 * @param {Function} config.templateProvider function to invoke via 
 * {@link ui.router.util.$templateFactory#fromProvider fromProvider}.
 * @param {object} params  Parameters to pass to the template function.
 * @param {object} locals Locals to pass to `invoke` if the template is loaded 
 * via a `templateProvider`. Defaults to `{ params: params }`.
 *
 * @return {string|object}  The template html as a string, or a promise for 
 * that string,or `null` if no template is configured.
 */
this.fromConfig = function (config, params, locals) {
  return (
    isDefined(config.template) ? this.fromString(config.template, params) :
    isDefined(config.templateUrl) ? this.fromUrl(config.templateUrl, params) :
    isDefined(config.templateProvider) ? this.fromProvider(config.templateProvider, params, locals) :
    null
  );
};

It seems that I'll either have to use $stateProvider.decorator, or hack ui-router's core. I think I might just do the latter and submit a PR. I'll be posting this issue on the github repo as well, to see if anyone on the ui-router team has a solution for this problem.

回答1:

Working plunk

you can use a resolve and templateProvider to do this.

  .state('child', {
      url: '/:child',
      resolve: {
        childTemplate: function ($stateParams, $templateRequest) {
          return $templateRequest($stateParams.child + ".html");
        }
      },
      templateProvider: function(childTemplate) { 
        return childTemplate;
      }
  });

This creates a resolve which uses the $stateParams to fetch the template (I'm using the $templateRequest to fetch, add to $templateCache, and return the contents all in one). Then, the resolved template content is injected into the view's templateProvider.