angular-ui-route解决与angularJS工厂

时间:2015-07-18 18:34:29

标签: angularjs ionic-framework angular-ui-router ionic angular-promise

我正在尝试使用$ stateProvider解析我创建的工厂

由于某种原因,工厂的承诺是一个空对象

但是当我从$ http调用中记录数据时,我从我的.json文件中获取数据

知道为什么我的defer.promise是一个空对象?

playlistsService.js

(function () {
    'use strict';

    angular
        .module('app.core')
        .factory('playlistsService', playlistsService);

    playlistsService.$inject = ['$http', '$q'];

    /* @ngInject */
    function playlistsService($http, $q) {
        var service = {
            loadPlaylists : loadPlaylists
        };

        return service;

        ////////////////

        function loadPlaylists() {
            var defer = $q.defer();
            $http.get('data/playlists.json')
                .success(function (data) {
                    console.log('json data: ' + angular.toJson(data));
                    defer.resolve(data);
                });
            console.log('defer.promise: ' + angular.toJson(defer.promise));
            return defer.promise;
        }
    }

})();

playlists.js

(function () {
    'use strict';

    angular
        .module('app.playlists')
        .config(stateProvider)
        .controller('Playlists', Playlists);

    stateProvider.$inject = ['$stateProvider'];
    Playlists.$inject = ['playlistsService'];

    /* @ngInject */
    function stateProvider($stateProvider){
        $stateProvider
            .state('app.playlists', {
                url: '/playlists',
                views: {
                    'menuContent': {
                        templateUrl: 'app/playlists/playlists.html',
                        controller: 'Playlists as vm',
                        resolve: {
                            playlists: function(playlistsService){
                                return playlistsService.loadPlaylists();
                            }
                        }
                    }
                }
            })
    }

    /* @ngInject */
    function Playlists(playlists) {
        /* jshint validthis: true */
        var vm = this;

        vm.activate = activate;
        vm.title = 'Playlists';
        vm.playlists = playlists;

        activate();

        ////////////////

        function activate() {
            console.log('playlists object: ' + angular.toJson(vm.playlists))
            console.log('playlists from service: ' + angular.toJson(playlists))
        }


    }

})();

1 个答案:

答案 0 :(得分:2)

您的Playlists控制器应具有$inject已在解析功能中创建的playlists承诺,而不是playlistsService即可。

Playlists.$inject = ['playlists'];

<强>更新

您还可以利用$http.get创建的承诺,而不是创建自定义承诺。

<强>服务

function loadPlaylists() {
     return $http.get('data/playlists.json')
     .then(function (data) {
         console.log('json data: ' + angular.toJson(data));
         return data;
     });
}

<强>解析

resolve: {
    playlists: function(playlistsService){
         return playlistsService.loadPlaylists();
    }
}