AngularJS之自定义服务详解(factory、service、provider)
前言
1、3种创建自定义服务的方式。
- Factory
- Service
- Provider
2、大家应该知道,AngularJS是后台人员在工作之余发明的,他主要应用了后台早就存在的分层思想。所以我们得了解下分层的作用,如果你是前端人员不了解什么是分层,那么你最好问问你后台的小伙伴。
dao层:就是Model层,在后台时,这一层的作用,就要是写与数据库交互数据的一层,在angularJS里就主要是写ajax的。
service层:主查写逻辑代码的,但在angularJS里也可以持久化数据(充当数据容器),以供不同的controller高用。
controller层:即控制层,在angularJS里就是写控制器的。控制器里尽量不要写那些不必要的逻辑,尽量写在service层里。
所以,就有了创建自定义服务的三种方式。
factory
factory方式创建的服务,作用就是返回一个有属性有方法的对象。相当于:varf=myFactory();
{{r}}
在自定义服务里注入服务示例,但不能注入$scope作用域对象。
service
通过service方式创建自定义服务,相当于new的一个对象:vars=newmyService();,只要把属性和方法添加到this上才可以在controller里调用。
{{r}}
3.provder
只有provder是能传.config()函数的service。如果想在service对象启用之前,先进行模块范围的配置,那就应该选择provider。需要注意的是:在config函数里注入provider时,名字应该是:providerName+Provider.
使用Provider的优点就是,你可以在Provider对象传递到应用程序的其他部分之前在app.config函数中对其进行修改。
当你使用Provider创建一个service时,唯一的可以在你的控制器中访问的属性和方法是通过$get()函数返回内容。