2017-01-10 42 views
0

$资源自定义的方法我有一个工厂:如何调用控制器

为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:

​​

W hy我的model.ads总是未定义?这不是在控制器中调用$resource自定义方法的正确方法吗?

+0

我认为你正在使用调用自定义资源的正确途径。我猜测错误在于你的API返回那个数据。检查你的chrome中的'Network'标签。查看API – tanmay

+0

返回的内容@tanmay我使用fiddler检查了WebApi,它工作正常。 –

回答

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

这很有趣,但为什么myService.query()没有承诺就能正常工作? –