Ionic控制器集成使用了Angularjs service服务。
1.1)、定义:
服务模块建议定义在项目的www/js/services.js
1.2)、作用:
之前讲controller的博文已经提过,controller尽量要轻量级,重量级的活(业务逻辑处理、数据持久化等)当然是留给service来干了。 考虑到内存性能, controllers 仅在需要的时候初始化,不需要了就会被丢弃。所以每次切换了url路由或者重载页面的时候,Angular 都会清空当前controller。而Services不一样,它可以提供办法让数据保持到整个application 的生命周期,还能够跨controllers 使用 。
1.3)、服务类型:
Angular 提供了3种方法提供 service。 Factory Service Provider
1.4)、Factory方式构造的service
Factory 方式用起来非常简单,只需要在factory里面定义好一个service对象,然后给他定义一些属性,最后返回service对象即可。 定义好了之后,是需要再controller方法中传递一下factory,就可以调用它的这些方法属性了。
1.4.1)、factory定义
angular.module('stater.services', []).factory('myFactory', function(){
var service = {};
var _artist = 'Nelly';
service.getArtist = function(){
return _artist;
}
return service;
});
1.4.2)、controller中调用factory服务
angular.module('starter.controllers', ['ionic']).controller('myFactoryCtrl', function($scope, myFactory){
$scope.artist= myFactory.getArtist();
});
1.5)、Service方式构造的service
使用Service, 会用js的"new"关键字来进行实例化。因此,可以在service中给"this"添加属性并返回"this"即可。而把 service 传进 controller 之后,在controller里就可以使用那些定义在 "this" 上的属性了。
1.5.1)、service定义
angular.module('stater.services', []).service('myService', function($http, $q){
var _artist = 'Nelly';
this.getArtist = function(){
return _artist;
}
});
1.5.2)、controller中调用service服务
angular.module('starter.controllers', ['ionic']).controller('myServiceCtrl', function($scope, myService){
$scope.artist= myService.getArtist();
});
1.6)、Provider方式构造的service
如果你想在 angular的.config()方法中就给service进行配置的话,前面两种方式是没办法做到的,只能通过Provider定义的方式才行。若想要在 service 对象可用之前就想要对服务进行模块范围的配置,那就需要使用 provider。1.6.1)、provider定义
angular.module('stater.services', []).provider('myProvider', function(){
this._artist = '';
//Going to set this property on the config function below
this.thingFromConfig = '';
//Only the properties/methods are on the object returned from $get are available in your controller. //这点需要注意
this.$get = function(){
return {
getArtist: function(){
return _artist;
},
thingOnConfig: this.thingFromConfig
}
}
});
1.6.2)、在config中调用provider服务配置赋值
angular.module('stater.routes', []).config(function(myProviderProvider){
//Providers are the only service you can pass into app.config
myProviderProvider.thingFromConfig = 'This sentence was set in app.config. Providers are the only service that can be passed into config. Check out the code to see how it works';
});
1.6.3)、controller中调用provider服务
angular.module('starter.controllers', ['ionic']).controller('myProviderCtrl', function($scope, myProvider){
$scope.artist= myProvider.getArtist();
$scope.data.thingFromConfig = myProvider.thingOnConfig;
});
1.7)、详细的例子请参考:
讲解:http://tylermcginnis.com/angularjs-factory-vs-service-vs-provider/ 代码:https://github.com/tylermcginnis/AngularServices