angular service学习笔记

1、service 是一个单例对象 —— 保证每次访问都是同一个对象

2、实现controller 和 directive 数据共享。

当你初试 Angular 时,很自然地就会往 controller 和 scope 里堆满不必要的逻辑。一定要早点意识到,controller 这一层应该很薄;也就是说,应用里大部分的业务逻辑和持久化数据都应该放在 service 里

Angular 提供了3种方法来创建并注册我们自己的 service。

1、 Factory

2、 Service

3、 Provider

 /**
* 定义ApiService服务
* 功能:专门向服务器发送post 和 get请求
* */
angular.module("myapp")
	.factory('myService1', ["$window", "$http", "$q", "$log",function($window, $http, $q, $log) {
		console.log("我是闭包部分的内容");
		// public api
		return {
			getUserData:function(){
				console.log("我是getUserData");
			},
			getOrgList:function(){
				console.log("我是getOrgList");
			},
			delUserById:function(userId){
				console.log("我来删除数据:" + userId);
			},
			// 作为共享的数据(可以缓存数据)
			shareData : {
				name:"huangbiao"
			}
		};
	}])
	//当前方法就是service
	.service("myService2",["$window", "$http", "$q", "$log",function($window, $http, $q, $log) {
//                console.dir($q);
	   this.serviceMethod = function(){
		   console.log("serviceMethod")
	   };
		this.serviceMethod2 = function(){
			console.log("serviceMethod2")
		};
		this.shareData = {
			name : "liumei",
			age : 18
		}
	}])
//            .provider("myServicePro",["$window", "$http", "$q", "$log",function($window, $http, $q, $log) {
	//Providers 是唯一一种你可以传进 .config() 函数的 service。当你想要在 service 对象启用之前,先进行模块范围的配置,那就应该用 provider。
	// 所以这种方式没有办法传入其他参数注入
	.provider("myServicePro",[ function() {
//                console.dir($q);
		console.log("我是闭包部分");

		this.$get = function(){
			console.log("我是闭包部分2");
			var resultService = {};
			resultService.myServiceProMethod = function(){
				console.log("serviceMethod")
			};
			resultService.myServiceProMethod2 = function(){
				console.log("serviceMethod2")
			};
			resultService.myServiceProShareData = {
				name : "huangbiao",
				age : 28
			}
			return resultService;
		};
	}]);
	
	
angular.module("myapp")
	.controller("AccordionDemoCtrl", ["$scope","myService1","myService2","myServicePro" ,
	function($scope,myService1,myService2,myServicePro) {
			myService1.getUserData();
			myService1.getOrgList();
			myService1.delUserById(123);
			$scope.before = function(){
				alert(myService1.shareData.name);
			};
			$scope.change = function(){
				myService1.shareData.name = "我变了";
			};

			console.dir(myService2);
			console.dir(myServicePro);

		}])

猜你喜欢

转载自hbiao68.iteye.com/blog/2366516