Last update: June 2014. I have partially rewritten this article to provide more technical details and also to show their differences more clearly.


Angular comes with different types of services. Each one with its own use cases.

Something important that you have to keep in mind is that the services are always singleton, it doesn’t matter which type you use. This is the desired behavior.

NOTE: A singleton is a design pattern that restricts the instantiation of a class to just one object. Every place where we inject our service, will use the same instance.

Provider

Provider is the parent of almost all the other services (all but constant) and it is also the most complex but more configurable one.

Let’s see a basic example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
app.provider('foo', function() {

  return {

    $get: function() {
var thisIsPrivate = "Private";
function getPrivate() {
return thisIsPrivate;
} return {
variable: "This is public",
getPrivate: getPrivate
};
} }; });

provider on its simplest form, just needs to return a function called $get which is what we inject on the other components. So if we have a controller and we want to inject this foo provider, what we inject is the $get function of it.

Why should we use a provider when a factory is much simple? Because we can configure a provider in the config function. We can do something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
app.provider('foo', function() {

  var thisIsPrivate = "Private";

  return {

    setPrivate: function(newVal) {
thisIsPrivate = newVal;
}, $get: function() {
function getPrivate() {
return thisIsPrivate;
} return {
variable: "This is public",
getPrivate: getPrivate
};
} }; }); app.config(function(fooProvider) {
fooProvider.setPrivate('New value from config');
});

Here we moved the thisIsPrivate outside our $get function and then we created a setPrivate function to be able to change thisIsPrivate in a config function. Why do we need to do this? Won’t it be easier to just add the setter in the $get? This has a different purpose.

Imagine we want to create a generic library to manage our models and make some REST petitions. If we hardcode the endpoints URLs, we are not making it any generic, so the idea is to be able to configure those URLs and to do so, we create a provider and we allow those URLs to be configured on a config function.

Notice that we have to put nameProvider instead of just name in our config function. To consume it, we just need to use name.

Seeing this we realize that we already configured some services in our applications, like $routeProvider and $locationProvider, to configure our routes and html5mode respectively.

Providers have two different places to make injections, on the provider constructor and on the $get function. On the provider constructor we can only inject other providers and constants (is the same limitation as the config function). On the $get function we can inject all but other providers (but we can inject other provider’s $get function).

Remember: To inject a provider you use: name + ‘Provider’ and to inject its $get function you just use name

Try it


Factory

Provider are good, they are quite flexible and complex. But what if we only want its $getfunction? I mean, no configuration at all. Well, in that cases we have the factory. Let’s see an example:

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
app.factory('foo', function() {
var thisIsPrivate = "Private";
function getPrivate() {
return thisIsPrivate;
} return {
variable: "This is public",
getPrivate: getPrivate
};
}); // or.. app.factory('bar', function(a) {
return a * 2;
});

As you see, we moved our provider $get function into a factory so we have what we had on the first provider example but with a much simpler syntax. In fact, internally a factory is a provider with only the $get function.

As I said before, all types are singleton, so if we modify foo.variable in one place, the other places will have that change too.

We can inject everything but providers on a factory and we can inject it everywhere except on the provider constructor and config functions.

Try it


Value

Factory is good, but what if I just want to store a simple value? I mean, no injections, just a simple value or object. Well angular has you covered with the value service:

Example:

1
app.value('foo', 'A simple value');

Internally a value is just a factory. And since it is a factory the same injection rules applies, AKA can’t be injected into provider constructor or config functions.

Try it


Service

So having the complex provider, the more simple factory and the value services, what is the service service? Let’s see an example first:

Example:

1
2
3
4
5
6
7
app.service('foo', function() {
var thisIsPrivate = "Private";
this.variable = "This is public";
this.getPrivate = function() {
return thisIsPrivate;
};
});

The service service works much the same as the factory one. The difference is simple: The factory receives a function that gets called when we create it and the servicereceives a constructor function where we do a new on it (actually internally is uses Object.create instead of new).

In fact, it is the same thing as doing this:

1
2
3
4
5
6
7
8
9
10
11
12
app.factory('foo2', function() {
return new Foobar();
}); function Foobar() {
var thisIsPrivate = "Private";
this.variable = "This is public";
this.getPrivate = function() {
return thisIsPrivate;
};
}

Foobar is a constructor function and we instantiate it in our factory when angular processes it for the first time and then it returns it. Like the service, Foobar will be instantiated only once and the next time we use the factory it will return the same instance again.

If we already have the class and we want to use it in our service we can do that like the following:

1
app.service('foo3', Foobar);

If you’re wondering, what we did on foo2 is actually what angular does with services internally. That means that service is actually a factory and because of that, same injection rules applies.

Try it


Constant

Then, you’re expecting me to say that a constant is another subtype of provider like the others, but this one is not. A constant works much the same as a value as we can see here:

Example:

1
2
3
4
app.constant('fooConfig', {
config1: true,
config2: "Default config2"
});

So… what’s the difference then? A constant can be injected everywhere and that includes provider constructor and config functions. That is why we use constant services to create default configuration for directives, because we can modify those configuration on our config functions.

You are wondering why it is called constant if we can modify it and well that was a design decision and I have no idea about the reasons behind it.

Try it


Bonus 1: Decorator

So you decided that the foo service I sent to you lacks a greet function and you want it. Will you modify the factory? No! You can decorate it:

1
2
3
4
5
6
7
8
9
app.config(function($provide) {
$provide.decorator('foo', function($delegate) {
$delegate.greet = function() {
return "Hello, I am a new function of 'foo'";
}; return $delegate;
});
});

$provide is what Angular uses internally to create all the services. We can use it to create new services if we want but also to decorate existing services. $provide has a method called decorator that allows us to do that. decorator receives the name of the service and a callback function that receives a $delegate parameter. That $delegate parameter is our original service instance.

Here we can do what we want to decorate our service. In our case, we added a greetfunction to our original service. Then we return the new modified service.

Now when we consume it, it will have the new greet function as you will see in the Try it.

The ability to decorate services comes in handy when we are consuming 3rd party services and we want to decorate it without having to copy it in our project and then doing there the modifications.

Note: The constant service cannot be decorated.

Try it


Bonus 2: Creating new instances

Our services are singleton but we can create a singleton factory that creates new instances. Before you dive deeper, keep in mind that having singleton services is the way to go and we don’t want to change that. Said that, in the rare cases you need to generate new instances, you can do that like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// Our class
function Person( json ) {
angular.extend(this, json);
} Person.prototype = {
update: function() {
// Update it (With real code :P)
this.name = "Dave";
this.country = "Canada";
}
}; Person.getById = function( id ) {
// Do something to fetch a Person by the id
return new Person({
name: "Jesus",
country: "Spain"
});
}; // Our factory
app.factory('personService', function() {
return {
getById: Person.getById
};
});

Here we create a Person object which receives some json to initialize the object. Then we created a function in our prototype (functions in the prototype are for the instances of the Person) and a function directly in Person (which is like a class function).

So we have a class function that will create a new Person object based on the id that we provide (well, it will in real code) and every instance is able to update itself. Now we just need to create a service that will use it.

Every time we call personService.getById we are creating a new Person object, so you can use this service in different controllers and even when the factory in a singleton, it generates new objects.

Kudos to Josh David Miller for his example.

Try it


Bonus 3: Coffeescript

Coffeescript can be handy with services since they provide a prettier way to create classes. Let’s see an example of the Bonus 2 using Coffeescript:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
app.controller 'MainCtrl', ($scope, personService) ->
$scope.aPerson = personService.getById(1) app.controller 'SecondCtrl', ($scope, personService) ->
$scope.aPerson = personService.getById(2)
$scope.updateIt = () ->
$scope.aPerson.update() class Person constructor: (json) ->
angular.extend @, json update: () ->
@name = "Dave"
@country = "Canada" @getById: (id) ->
new Person
name: "Jesus"
country: "Spain" app.factory 'personService', () ->
{
getById: Person.getById
}

It is prettier now in my humble opinion.

Try it


NOTE: This last one, being Coffeescript seems to fail a little bit with JSbin. Go to the Javascript tab and select Coffeescript to make it work.

Conclusion

Services are one of the coolest features of Angular. We have a lot of ways to create them, we just need to pick the correct one for our use cases and implement it.

If you found any issue or you think that this can be improved, please leave an issue or pull request at Github. In any case, a comment will be appreciated :).

http://angular-tips.com/blog/2013/08/understanding-service-types/

Understanding Service Types的更多相关文章

  1. 浅析Kubernrtes服务类型(Service Types)

    先上图 在Kubernetes集群中,service通过标签选择器选着对应的pod,然后对请求进行转发,看个动画,能直接了当体会到便签选择器 pod,endpoints,service三者关系 1.举 ...

  2. Learning WCF Chapter1 Generating a Service and Client Proxy

    In the previous lab,you created a service and client from scratch without leveraging the tools avail ...

  3. Learning WCF Chapter1 Exposing Multiple Service Endpoints

    So far in this chapter,I have shown you different ways to create services,how to expose a service en ...

  4. Service Fabric Cluster Manager

    作者:潘罡 (Van Pan)@ Microsoft 我们回到Service Fabric最底层的话题,谈谈Service Fabric是怎么工作的. 首先,我们回到下面的文档,看看Service F ...

  5. service fabric docker 安装

    1. 镜像拉取 docker pull microsoft/service-fabric-onebox 2. 配置docker(daemon.json) { "ipv6": tru ...

  6. F#之旅2 - 我有特别的学F#技巧

    原文地址:https://swlaschin.gitbooks.io/fsharpforfunandprofit/content/learning-fsharp/ Learning F#Functio ...

  7. WCF服务与WCF数据服务的区别

    问: Hi, I am newbie to wcf programming and a little bit confused between WCF Service and WCF Data  Se ...

  8. wcf中的File-less Activation

    File-less Activation Although .svc files make it easy to expose WCF services, an even easier approac ...

  9. Eclipse MAT: Understand Incoming and Outgoing References

    引用:http://xmlandmore.blogspot.hk/2014/01/eclipse-mat-understand-incoming-and.html?utm_source=tuicool ...

随机推荐

  1. 关于Java中形参与实参的理解

    今天阅读了一个写的非常棒的博文,通过此博文再次复习了Java中参数传递的知识(即值传递与引用传递的区别).参考网站http://www.cnblogs.com/binyue/p/3862276.htm ...

  2. windows7安装远程服务器AD域管理工具

    目的:在win7上安装“远程服务器管理工具”,这样可以在客户端进行对服务器的AD域的操作,避免了远程登陆进服务器的麻烦. 前提条件:一般此工具只有管理员才具有有效使用权限,所以,在域administr ...

  3. 使用CSS创建有图标的网站导航菜单

    在我创建的每一个互联网应用中,我都试图避免创建完全由图片组成的菜单.在我看来,网页菜单系统中应该使用文字.这样做也会让菜单变得更干净利落.清晰和易读,不用考虑应用程序如何读取它,以及页面放大的时候也不 ...

  4. event.preventDefault()

    <!doctype html> <html lang="en"> <head> <meta charset="utf-8&quo ...

  5. GoldenGate中使用FILTER,COMPUTE 和SQLEXEC命令

    本文主要介绍OGG中一些过滤或计算函数的用法,以及sqlexec的基本用法 SQLPREDICATE 在使用OGG初始化时,可以添加此参数到extract中,用于选择符合条件的记录,下面是OGG官方文 ...

  6. HBase分布式安装

    安装HBase之前需要先安装Hadoop,因为HBase是运行在Hadoop集群上的.安装Hadoop可以参照http://www.cnblogs.com/stGeekpower/p/3307289. ...

  7. php读取文件时多了个%uFEFF[bom字符],怎样去掉?

    今天从记事本文件中读取静态生成记录时,发现读出来的第一个链接打开的时候总是提示非法操作,把鼠标放到链接上发现链接的前面多了个%uFEFF, 百度一查,原来这是好多人都有遇到过的bom头问题,特地记录下 ...

  8. 如何验证 jemalloc 优化 Nginx 是否生效

    Jemalloc 源于 Jason Evans 2006年在 BSDcan conference 发表的论文:<A Scalable Concurrent malloc Implementati ...

  9. LotusPhp中配置文件组件LtConfig详解

    LotusPhp中配置文件组件LtConfig是约定的一个重要组成部分,适用于多个场景,多数的LotusPhp组件如数据库,缓存,RBAC,表单验证等都需要用到配置组件,LtConfig配置组件也是L ...

  10. Eclipse之Failed to load the JNI shared library”……\jvm.dll”的解决方案

    问题描述:java环境变量配置完全正确,但是运行eclipse时提示:Failed to load the JNI shared library " xxx\jva.dll" 原因 ...