javascript 单独文件中的 AngularJS 服务

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13395686/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 18:38:32  来源:igfitidea点击:

AngularJS service in separate file

javascriptmodel-view-controllerangularjsproject-structure

提问by ChruS

My app.js contains

我的 app.js 包含

var app = angular.module('myApp', []).
config(['$routeProvider', function ($routeProvider, $http) {
    ...
}]);

Service looks like

服务看起来像

app.service('MyService', function () {
    addNums = function (text) {
        return text + "123";
    }
});

And in contoller I have

在控制器中我有

function adminCtrl ($scope, MyService) {
    $scope.txt = MyService.addNums("abc");
};

They are all in separate files. The problem is that I'm getting an error Unknown provider: MyServiceProvider <- MyService

它们都在单独的文件中。问题是我遇到了错误 Unknown provider: MyServiceProvider <- MyService

Looks like I'm doing something wrong.

看起来我做错了什么。

回答by Mark Rajcok

The provider error can occur if you forgot to tell Angular to load your myApp module. E.g., do you have this in your index.html file?:

如果您忘记告诉 Angular 加载 myApp 模块,则可能会发生提供程序错误。例如,你的 index.html 文件中有这个吗?:

<html ng-app="myApp">

Your service is missing "this.":

您的服务缺少“这个”:

this.addNums = function(text) {

Fiddle.

小提琴



There seems to be a lot of confusion in the Angular community about when to use service() vs factory(), and how to properly code them. So, here's my brief tutorial:

Angular 社区似乎对何时使用 service() 和 factory() 以及如何正确编码它们存在很多困惑。所以,这是我的简短教程:

The service() methodexpects a JavaScript constructor function. Many Angular code examples that use service() contain code that is not a constructor function. Often, they return an object, which kind of defeats the purpose of using service() — more about that below. If an object needs to be created and returned, then factory() can be used instead. Often, a constructor function is all that is needed, and service() can be used.

service()方法需要一个JavaScript构造函数。许多使用 service() 的 Angular 代码示例包含不是构造函数的代码。通常,它们返回一个对象,这违背了使用 service() 的目的——更多关于下面的内容。如果需要创建和返回对象,则可以使用 factory() 代替。通常,只需要一个构造函数,并且可以使用 service()。

The quotes below are from different AngularJS Google Group posts:

以下引用来自不同的 AngularJS Google Group 帖子:

The main difference between using factory() vs service() is that factory() must return an object, while service() doesn't return anything but it must be an object constructor function.

Use factory() if the function you are providing builds the object you want. I.e., Angular will essentially do
obj = myFactory()
to get the obj. Use service() if the function you are providing is a constructor for the object you want. I.e., Angular will essentially do
obj = new myService()
to get/instantiate the obj.

使用 factory() 与 service() 的主要区别在于 factory() 必须返回一个对象,而 service() 不返回任何内容,但它必须是一个对象构造函数。

如果您提供的函数构建了您想要的对象,请使用 factory()。即,Angular 本质上会执行
obj = myFactory()
来获取 obj。如果您提供的函数是您想要的对象的构造函数,请使用 service()。即,Angular 本质上会执行
obj = new myService()
来获取/实例化 obj。

So when people use service() and its code "return"s an object, it is kind of a waste because of the way JavaScript "new" works: "new" will first create a brand new JavaScript object (then do stuff with prototype, then call the function defined by myService(), etc. -- details we don't really care about here), but because the function defined by myService() returns its own object, "new" does something a bid odd: it throws away the object is just spent time creating and returns the object that the myService() function created, hence the "waste".

因此,当人们使用 service() 并且它的代码“返回”一个对象时,由于 JavaScript “new” 的工作方式,这有点浪费:“new”将首先创建一个全新的 JavaScript 对象(然后使用原型进行操作) ,然后调用由 myService() 等定义的函数——这里我们并不真正关心细节),但是因为由 myService() 定义的函数返回它自己的对象,“new”做了一些奇怪的事情:它丢弃对象只是花时间创建并返回 myService() 函数创建的对象,因此是“浪费”。

One of the reasons that service() was introduced was to make it easy to use "classical" OO techniques, such as defining your service as a coffeescript class.

引入 service() 的原因之一是使使用“经典”OO 技术变得容易,例如将您的服务定义为一个 coffeescript 类。

Also, the undocumented naming convention for services seems to be camelCase with first letter lowercased: e.g., myService.

此外,未公开的服务命名约定似乎是驼峰式,首字母小写:例如,myService。

回答by Brian Chapman

You need to return addNums in app.service callback.

您需要在 app.service 回调中返回 addNums。

app.service('MyService', function () {
  addNums = function (text) {
    return text + "123";
  }
  return addNums;
});

Now, whenever you use MyService, angular will give you back the addNums function to use.

现在,无论何时使用 MyService,angular 都会返回 addNums 函数供您使用。

Therefore, you should use it in your controller like so (note there isn't the addNums call):

因此,您应该像这样在控制器中使用它(注意没有 addNums 调用):

function adminCtrl ($scope, MyService) {
  $scope.txt = MyService("abc");
};

回答by Ryan O'Neill

Just as an added clarification on Brian's answer, if you wanted to still have your code call MyService.addNums you could use the following:

正如对布赖恩回答的补充说明一样,如果您仍然想让代码调用 MyService.addNums,您可以使用以下内容:

app.service('MyService', function() {
    var result = {};
    result.addNums = function (text) {
        return text + "123";
    };

    return result;
});

Then you could still use

那么你仍然可以使用

MyService.addNums("abc");

if you wanted to do so.  

如果你想这样做。