【问题标题】:How do we call a function type returned by a Service in Angular我们如何在 Angular 中调用 Service 返回的函数类型
【发布时间】:2016-05-29 05:56:25
【问题描述】:

好吧,我在澄清我对 Angular Servcies 和工厂的疑虑时,偶然发现了一个根据返回类型对其进行描述的教程。

目前我有以下内容:

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

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

然后我有:

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

    $scope.serviceData = Service;
    $scope.factoryData = Factory;

});

正如教程所说,服务返回整个函数本身,而工厂返回字符串“tried”。这很好。

现在我的意思是,如果我返回了一个函数类型,并且由于它也不接受任何参数,我仍然会以某种方式正确执行该函数。所以不知何故,我也从 Service 中得到了“尝试”。

参考JS function.prototype.call(),我试过了

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

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

});

这似乎不起作用。 在上述情况下,如何获取字符串“已尝试”。??

注意:我在编写服务时非常熟悉“this”的使用。但在这里我的问题不仅仅是关于 Angular 中的服务,而是关于在 JS 中调用返回的函数

【问题讨论】:

标签: javascript angularjs function service call


【解决方案1】:

要做到这一点,您需要从服务中返回一个函数:

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>

【讨论】:

  • 已经试过了:这不起作用。错误:服务不是函数
  • @SaurabhTiwari 你说“如果我返回了一个函数类型”,所以我认为服务正在返回一个函数。它实际上应该返回一个函数。查看更新。
  • 服务使用this...没有真正需要返回任何东西。答案看起来更像工厂
  • @T J :我完全明白你的意思,我知道你修改我的函数以返回一个函数的方式。但是提出这个问题的重点是使用原始帖子中的通用功能来显示工厂和服务之间的区别。这是否意味着,我无法使用原始案例检索所需的输出
  • @charlietfl 它应该是,但这是问题的答案 ""How do I get the string "tried" in above case.??" "
【解决方案2】:

您必须像这样定义服务:

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

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

然后像这样在控制器中获取返回值:

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

    $scope.serviceData = Service.output();

});

【讨论】:

  • 嗨,Amin,我非常熟悉您编写服务的方式。但在这里我的问题不仅仅是关于 Angular 中的服务,而是关于在 JS 中调用返回的函数
  • 这是一般使用服务的想法(尽管使用工厂可以实现相同的结果)这是服务和工厂之间的区别之一,服务不返回它们的值全局范围
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-05
  • 2022-01-07
  • 2022-08-18
  • 1970-01-01
  • 1970-01-01
  • 2014-11-14
相关资源
最近更新 更多