AngularJS:控制器中的工厂函数未定义

时间:2015-06-11 09:41:35

标签: angularjs asynchronous angularjs-service angularjs-controller angularjs-factory

我过去常常以同样的方式工作,这让我发疯了。我想对工厂执行$ http GET调用,然后将结果返回到控制器中进行处理。

工厂(不要注意请求网址的疯狂):

App.factory('MessageFactory', function ($http) {
        var MessageFactory = {
            getCast: function () {
                var request = {
                    method: "GET",
                    url: spHostUrl + "/_api/web/Lists/getByTitle('" + listTitle + "')/items?$select=AuthorId,Author/Name,Author/Title,Type_x0020_message,Title,Modified,Body,Expires,Attachments&$expand=Author/Id",
                    headers: {
                        "Content-Type": "application/json;odata=verbose",
                        "Accept": "application/json;odata=verbose"
                    }
                };

                $http(request)
                .then(function (res) {
                    return res.data;
                }).catch(function (res) {
                    console.error("error ", res.status, res.data);
                }).finally(function () {
                    console.log("end");
                });
            }
        };
        return MessageFactory;
    });

现在控制器

App.controller('MessageController', function ($scope, $http, $log, $attrs, MessageFactory) {
        $scope.messages = MessageFactory;
        MessageFactory.getCast().then(function (asyncCastData) {
            $scope.messages.cast = asyncCastData;
        });
        $scope.$watch('messages.cast', function (cast) {
            //do stuff
        });
});

当我测试它时,我收到以下错误:

  

错误:MessageFactory.getCast(...)未定义   @ /脚本/ App.js:167:9

第167行确实是控制器中的这一行

MessageFactory.getCast().then(function (asyncCastData) {

我的应用程序适用于任何其他功能,所以我的问题出现在添加此部分时,我很确定我的控制器还不知道我的工厂,因此尝试访问他的功能。因为它是异步调用,所以它应该与控制器中的代码一起使用。我需要你的帮助,谢谢。

1 个答案:

答案 0 :(得分:3)

  

你必须得到。然后是未定义的错误

因为您错过了从服务方式返回承诺。

<强>服务

var MessageFactory = {
  getCast: function() {
    var request = {
      method: "GET",
      url: spHostUrl + "/_api/web/Lists/getByTitle('" + listTitle + "')/items?$select=AuthorId,Author/Name,Author/Title,Type_x0020_message,Title,Modified,Body,Expires,Attachments&$expand=Author/Id",
      headers: {
        "Content-Type": "application/json;odata=verbose",
        "Accept": "application/json;odata=verbose"
      }
    };

    return $http(request) //returned promise from here
      .then(function(res) {
        return res.data;
      }).catch(function(res) {
        console.error("error ", res.status, res.data);
      }).finally(function() {
        console.log("end");
      });
    }
};
相关问题