如何在控制器中调用$ resource自定义方法

时间:2017-01-10 08:15:35

标签: javascript angularjs asp.net-web-api angular-resource

我有一家工厂:

为myService:

'use strict';
app.factory('myService', ['$resource', 'ngAuthSettings', function ($resource, ngAuthSettings) {
  var serviceBase = ngAuthSettings.apiServiceBaseUri;

  return $resource(serviceBase + 'api/category/', {}, {
    update: {
      method: 'PUT'
    },
    getAllByCategory: {
      url: serviceBase + 'api/category/GetAllByCategory',
        method: 'GET', isArray: true
    }
  });
}]);

然后我有一个控制器:

searchController:

'use strict';
app.controller('searchController',
    ['ngAuthSettings', '$scope', 'myService', '$routeParams', '$location',
    function (ngAuthSettings, $scope, myService, $routeParams, $location) {

    function init() {
        var search = $location.search();
        var keywords = search.keywords;            

        var model = myService.getAllByCategory({ categoryId: 2, page: $routeParams.page });

        $scope.categoryAds = model.ads;
        $scope.bigTotalItems = model.totalCount;
        $scope.maxSize = ngAuthSettings.maxPagingSize;
    }
    init();
}]);

为什么我的model.ads始终未定义?这不是在控制器中调用$resource自定义方法的正确方法吗?

1 个答案:

答案 0 :(得分:0)

由于回复可能需要一些时间,但你是非常直接地添加作业,因此它发生在资源之后将其置于承诺/行动中,

'use strict';
    app.controller('searchController', ['ngAuthSettings', '$scope', 'myService', '$routeParams', '$location',
        function (ngAuthSettings, $scope, myService, $routeParams, $location) {
            function init() {
                var search = $location.search();
                var keywords = search.keywords;            
                var model = myService.getAllByCategory({ categoryId: 2, page: $routeParams.page }, 
                    function() {
                        $scope.categoryAds = model.ads;
                        $scope.bigTotalItems = model.totalCount;
                        $scope.maxSize = ngAuthSettings.maxPagingSize;
                    }
                );

            }
            init();
        }
    ]);