Angular-service TypeError:无法读取属性' saveURL'未定义的

时间:2016-08-23 20:45:51

标签: angularjs angular-services

我正在尝试编写一个服务来存储URL的查询字符串。我这样做是通过将其存储在cookie中然后检索它。但是当我尝试从控制器访问saveURL方法以添加查询字符串时,我收到此错误:

TypeError:无法读取属性' saveURL'未定义的

controller.js

angular
    .module("app.alerts.alertView")
    .controller("AlertViewsController", AlertViewsController);

    AlertViewsController.$inject = [
        "$scope", "$location", "alertHistory"
    ];

    function AlertViewsController($scope, $location, alertHistory) {
        alertHistory.saveURL($location.search());
    } 

service.js

(function () {
    "use strict";

    angular
        .module("app.alerts.alertView")
        .service("alertHistory", alertHistory);

    alertHistory.$inject = [
        "$cookieStore"];

    function alertHistory ($cookieStore) {
        return {
            saveURL: function (urlObj) {
                var array = $cookieStore.get("key");
                array.push(urlObj);
                $cookieStore.put("key", array);
            }
        };
    }
})();

我已正确注入服务。还有什么可以纠正以解决错误。请帮忙

1 个答案:

答案 0 :(得分:0)

看起来发生的事情是你没有返回你认为你正在返回的东西,因为返回对象不够具体,JS不能继续。此外,您忘记注入$location服务。我会尝试重写如下:

angular
    .module("app.alerts.alertView")
    .service("alertHistory", [ '$cookieStore', function ($cookieStore) {
    var x = {};
    x.saveURL = function (urlObj) {
        var array = $cookieStore.get("key");
        array.push(urlObj);
        $cookieStore.put("key", array);
    };
    return x;
}]).controller('AlertViewsController', [ '$scope', '$location', 'alertHistory', function ($scope, $location, alertHistory) {
    alertHistory.saveURL($location.search());
}]);