当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - How do we call a function type returned by a Service in Angular

问题描述:

Well, I was clarifying my doubts on Angular Servcies and factories and came across a tutorial which describes it on the basis of return types.

Currently I have following :

angular.module("Training").service("Service", tryDis);

angular.module("Training").factory("Factory", tryDis);

function tryDis(){

console.log("trying..");

return "tried";

}

and then I have :

angular.module("Training").controller("Ctrl1", function($scope,Service, Factory){

$scope.serviceData = Service;

$scope.factoryData = Factory;

});

As the tutorial says service returns the whole function itself, while factory returns the string "tried". This was very well.

Now my point is if I have a function type returned and since it do not take any arguments too, I shall still somehow get the function executed right. So that somehow I get "tried" from Service too.

Referring to JS function.prototype.call(), I tried

angular.module("Training").controller("Ctrl1", function($scope,Service, Factory){

$scope.serviceData = this.call(Service);//also call(Service)

$scope.factoryData = Factory;

});

This doesn't seem to work.

How do I get the string "tried" in above case.??

Note: I am pretty familiar with use of 'this' while writing services. But here my question is not just regarding services in Angular, rather its about calling a returned function in JS

网友答案:

To be able to do that you need to return a function from the service:

angular.module('test', [])
  .controller('testCtrl', function(testService) {
    console.log(testService())
  })
  .service('testService', function() {
      return function() {
        return 'tried';
      };
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="test" ng-controller="testCtrl"></div>
网友答案:

You must define the service like this:

angular.module("Training").service("Service", tryDis);

function tryDis(){
    this.output=function(){
        console.log("trying..");
        return "tried";
    };
}

and then get the returned value in your controller like this:

angular.module("Training").controller("Ctrl1", function($scope,Service, Factory){

    $scope.serviceData = Service.output();

});
分享给朋友:
您可能感兴趣的文章:
随机阅读: