search

Home  >  Q&A  >  body text

angular.js - Preloading and controller injection of angular-ui-router

After

ui-router's 预加载 resolve obtains data, how to inject it into the controller?

Remarks:

Routing code ↓

$stateProvider.state('dashboard', {
    url: '/dashboard',
    templateUrl: 'views/dashboard/index.html',
    resolve: {
        getList: function ($stateParams, $NetRequest){
            var options = {type: 'charts'};
            
            $NetRequest.post(options).then(function($ref){
                return $ref.data;
            });
        }
    },
    controllerUrl: 'views/dashboard/index',
    controller: 'DashboardController',
    controllerAs: 'vm'
});

Service Code ↓

service.post = function($options){
    var deferred = $q.defer();
    
    // 省略请求函数...
    
    return deferred.promise;
};

If you inject getList directly into the controller at this time, the result will be undefined.

I read the official documentation and there is a $inject parameter, but unfortunately there is no example. I don’t know how to use it.

ringa_leeringa_lee2868 days ago589

reply all(2)I'll reply

  • 仅有的幸福

    仅有的幸福2017-05-15 17:13:59

    The problem is solved, the method is actually very simple - -

    $stateProvider.state('dashboard', {
        url: '/dashboard',
        templateUrl: 'views/dashboard/index.html',
        resolve: {
            getList: function ($stateParams, $NetRequest){
                var options = {type: 'charts'};
                
                return $NetRequest.post(options);
                // 因为 $NetRequest.post 已经返回了结果
            }
        },
        controllerUrl: 'views/dashboard/index',
        controller: 'DashboardController',
        controllerAs: 'vm'
    });

    reply
    0
  • 漂亮男人

    漂亮男人2017-05-15 17:13:59

    '//Get data here'. . . . Did you return your promise?

    reply
    0
  • Cancelreply