AngularJS控制器之间的共享服务

时间:2015-09-24 17:21:39

标签: angularjs

我的共享服务存在问题。 我创建了一个看起来像这样的服务:

.factory('ConfiguratorService', ['$q', 'ColourService', 'Moltin', 'ArrayService', function ($q, colourService, moltin, arrayService) {

    // Gets a new kit or gets from the session
    var getKit = function () {

        // Create the base model
        var model = {
            name: '',

            garments: [],
            totalPrice: 0,

            colour1: '',
            colour2: '',
            colour3: '',

            team: {
                name: '',
                sport: '',

                colour1: '',
                colour2: '',
                colour3: ''
            }
        };

        // If we have our model in the session, then return that otherwise use the base model
        return sessionStorage.designer ? angular.fromJson(sessionStorage.designer) : model;
    };

    // Declare our service
    var service = {

        // Define our properties
        selectedColours: [],
        selectedLeisureColours: [],
        kit: getKit(),

        // Init
        init: function (slug) {

            // Get our Sport
            return service.getSport(slug).then(function (response) {

                // If we get our sport, get our colours
                return colourService.list();

            // If we get our colours
            }).then(function (response) {

                // Add them to our service
                service.colours = response;
            });
        },

        // Gets our sport by it's slug
        getSport: function (slug) {

            // Defer our promise
            var deferred = $q.defer();

            // If we have a slug 
            if (slug) {

                // Return the category
                moltin.categories.get(slug).then(function (response) {

                    // Assign our response to the service
                    service.sport = response;

                    // If we have a response
                    if (response) {

                        // Assign our sport to our team
                        service.kit.team.sport = response.slug;
                    }

                    // Resolve our promise
                    deferred.resolve(response);
                });

            // Otherise, nothing was supplied
            } else {

                // Resolve anyway
                deferred.resolve();
            }

            // Return our promise
            return deferred.promise;
        },

        // Saves the session to the session storage
        saveSession: function () {

            // Store our model in the session
            sessionStorage.designer = angular.toJson(service.kit);
        },

        // Clears the session
        clearSession: function () {

            // Remove our model from the session
            sessionStorage.removeItem('designer');
        }
    };

    // Return our service
    return service;
}])

我有一个调用init函数的控制器,一切正常。 我遇到的问题是,在下一个视图中,控制器(即使我在控制台注销服务时显示所有内容)也没有将颜色分配给范围。

我的控制器看起来像这样:

.controller('DesignerTeamController', ['PageTitle', 'ConfiguratorService', 'ColourService', function (pageTitle, configuratorService, colourService) {
    var self = this;

    pageTitle.setTitle('Kudos Sports - Choose your team');

    console.log(configuratorService);

    // Assign our models
    self.colours = configuratorService.colours;
    self.range = [1, 2, 3];

    // Set our colours
    self.setColour = configuratorService.setColour;
}])

console.log(configuratorService); 实际上将 configuratorService.colours 显示为包含30个项目的数组。但是,如果我控制台.log(self.colours)我得到了未定义。

有谁知道为什么?

1 个答案:

答案 0 :(得分:4)

出现问题是因为在getSport(slug)回调执行赋值之前,服务对象中没有colors属性。

您可以通过以下两种方式管理:

1)将属性指定为在回调中更新的空数组。然后该属性在控制器中不会被定义,因为它是一个数组,将创建一个引用

var service = {
    colours:[]
    .....
}

不要破坏回调中的数组引用,只需更新数组

即可
// If we get our colours
}).then(function (response) {
     // Add them to our service
     service.colours.concat( response);
});

2)另一种方法是将整个服务对象分配给控制器中的变量:

// Assign our models
self.configModel = configuratorService;

然后在视图中,您可以将colours属性添加到configModel对象:

ng-if="vm.configModel.colours.length"