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

How to call $resource custom method in controller

我有一个工厂:

我的服务:

'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
    }
  });
}]);

然后我有一个控制器:

搜索控制器:

'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 自定义方法的正确方法吗?

由于响应可能需要一些时间,但您正在非常立即地添加分配,因此它发生在 promise/action 资源之后,

'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();
        }
    ]);