javascript – 单独文件中的AngularJS服务

前端之家收集整理的这篇文章主要介绍了javascript – 单独文件中的AngularJS服务前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我的app.js包含
var app = angular.module('myApp',[]).
config(['$routeProvider',function ($routeProvider,$http) {
    ...
}]);

服务看起来像

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

在控制器中我有

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

它们都在单独的文件中.问题是我收到了错误
未知提供者:MyServiceProvider< - MyService 看起来我做错了什么.

解决方法

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

您的服务缺少“这个.”:

this.addNums = function(text) {

Fiddle.

Angular社区似乎有很多关于何时使用service()vs factory()以及如何正确编码它们的混淆.所以,这是我的简短教程:

service() method需要JavaScript constructor function.许多使用service()的Angular代码示例包含的代码不是构造函数.通常情况下,他们会返回一个对象,这会破坏使用service()的目的 – 更多关于下面的内容.如果需要创建并返回一个对象,则可以使用factory()代替.通常,只需要构造函数,并且可以使用service().

以下引用来自不同的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.

因此,当人们使用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.

此外,服务的未记录命名约定似乎是camelCase,首字母小写:例如,myService.

原文链接:https://www.f2er.com/js/159246.html

猜你在找的JavaScript相关文章