简体   繁体   English

这个 Angular 代码有什么问题?

[英]What's wrong with this Angular code?

angular.module('events.services', [])
    .factory('EventService', function($http, $cordovaSQLite) {
        return {
            test: function() {
                return 'It Works!';
            }
        }
    }
})

Controller控制器

.controller('NearCtrl', function($scope, $http, $cordovaSQLite, EventService) {
    var test = EventService.test;
    console.log(test); // I expect 'It works' to be here, but returns 'function test();'
})

Why doesn't this return 'It Works!'为什么这不返回“它有效!” ? ? Thanks a lot.非常感谢。

As per comments, and as per the JS language根据评论,以及根据 JS 语言

In the following link在以下链接中

Calling functions Defining a function does not execute it.调用函数 定义一个函数并不执行它。 Defining the function simply names the function and specifies what to do when the function is called.定义函数只是简单地命名函数并指定调用函数时要执行的操作。 Calling the function actually performs the specified actions with the indicated parameters.调用该函数实际上使用指定的参数执行指定的操作。 For example, if you define the function square, you could call it as follows:例如,如果您定义函数 square,您可以按如下方式调用它:

square(5);

As you can see, the function requires () to be executed.如您所见,该函数需要执行()

function square(num){
  return num
}

console.log(square);
=> function square(num)

console.log(square( 5 ));
=> 5

As you are using your factory,当您使用您的工厂时,

console.log(EventService);
=> { test: function() { return 'It Works!'; }

In your scenario, your factory has returned an object with a property test that points to an anonymous function.在您的场景中,您的工厂返回了一个带有指向匿名函数的属性测试的对象。

Simply calling EventService.test returns the anonymous function just as it did when we called console.log(square);简单地调用EventService.test返回匿名函数,就像我们调用console.log(square) 一样; . . To utilize the returned function value you must also call it like so要利用返回的函数值,您还必须像这样调用它

EventService.test();

Continue to post questions as you see fit, but also remember to troubleshoot your code first, and if you still need to ask a question include all the steps you took to troubleshoot your problem :)继续发布您认为合适的问题,但也要记住先对代码进行故障排除,如果您仍然需要提出问题,请包括您为解决问题所采取的所有步骤:)

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

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