简体   繁体   English

如何使用angular.js Web API将API调用controller.js发送到service.js?

[英]how to send api call controller.js to service.js using angular.js web api?

I want to send api call controller.js to service.js in my demo.i am show user list in demo and i am used for angularjs datatable with web api.and my structure is app.js,controller.js,service.js this 3 separate file is used. 我想在我的演示中将api调用controller.js发送到service.js。我在演示中显示用户列表,我用于Web api的angularjs数据表。我的结构是app.js,controller.js,service.js使用这3个单独的文件。 then i want to send call service.js. 然后我想发送呼叫service.js。

this is my simple controller.js code working well. 这是我简单的controller.js代码,效果很好。

app.controller('userscontroller', ['$scope', '$http', 'DTOptionsBuilder', 'DTColumnBuilder', 'userservice',
function ($scope, $http, DTOptionsBuilder, DTColumnBuilder, userservice) {

    $scope.dtColumns = [
        DTColumnBuilder.newColumn("fullName", "Full Name").withOption('name', 'firstname'),            
        DTColumnBuilder.newColumn("email", "Email").withOption('name', 'email'),            
    ]

    $scope.dtoptions = dtoptionsbuilder.newoptions().withoption('ajax', {
        datasrc: "data",
        url: "/home/getuserlist",            
        type: "post",
        data: { 'type': "time"},            
    })
    .withoption('processing', true) 
    .withoption('serverside', true) 
    .withpaginationtype('full_numbers') 
    .withdisplaylength(10)
    .withoption('aasorting', [0, 'asc'])       

}])

this my service.js file: 这是我的service.js文件:

app.service('userservice', function ($http) {});

any one have idea how to call this api call using service.js then please let me know. 任何人都知道如何使用service.js调用此api调用,然后让我知道。

Based on your comments, you can do it like this: 根据您的评论,您可以这样做:

Your user service: 您的用户服务:

app.service('userservice', ['$http', '$q', function ($http, $q) {

  function getuserlist(data){
    var defer = $q.defer();
    $http.post('/home/getuserlist', data)
    .then(function(result){
       defer.resolve(result.data);
    }); 
    return defer.promise;
  }

  return {
    getUsers: getuserlist
  };
}]);

Then, in your controller, you can utilize fromFnPromise function, something like this: 然后,在您的控制器中,您可以利用fromFnPromise函数,如下所示:

vm.dtOptions = DTOptionsBuilder.fromFnPromise(function() {
        return userservice.getUsers(data);
    })
    //rest of your options

You can find more details about fromFnPromise method on this link . 您可以在此链接上找到有关fromFnPromise方法的更多详细信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM