Service和Factory等头等舱和经济舱的区别别

angularjs 中 Factory,Service,Provider 之间的区别
发布时间: 10:13:04
本片文章是使用了&&的code() 来进行演示&Factory,Service,Provider 之间的区别
1. Factory
factory('dataService',function(){
golbal_sitename:"this is the shared value",
sayHello:function(msg){
alert(msg);
注意看上面的代码,我们定义dataService 里面 ,后面的funciton 直接返回的是一个对象。 反回对象里面可以定义属性和方法,上面就是返回了一个golbal_sitename属性和sayHello方法。
简单点说就是: 在factory 定义的function 返回的对象上面定义些属性和方法, 等注入到controller后,就可以在controller调用这些属性和方法了。
2. 我们来用service改写上面的代码
service('dataService',function(){
this.golbal_sitename = "this is the shared value";
this.sayHello = function(msg){
alert(msg);
注意上面的代码和factory 定义的区别,这里我们去掉了return 添加了this。换句话说 factory 定义里面的function 其实是返回个对象,而service 定义里面的funciton 返回的是个类定义。
也就是说service 里面定义的dataService 最后是通过new 后面定义的function 来实例化的。
3. 使用Provider再次改写代码
Provider 定义的 service 可以传进 .config() 函数。当我们需要在service 启用前配置其模块参数时,就需要使用Provider来定义service.
代码如下:
provider('dataService',function(){
this.$get = function(){
golbal_sitename:"this is the shared value",
sayHello:function(msg){
alert(msg);
上面使用三种方式定义的service 都可以正常工作, 唯一需要注意的就是使用当service 需要传入到config中进行配置的时候,一定要使用provider进行定义。
来源:/slardar1978/p/4203979.html2153人阅读
AngularJS(16)
初学 AngularJS 时, 肯定会对其提供 factory 、 service 和 provider 感到疑惑, 这三种都是提供服务的方式, 他们到底有什么区别呢?
factory 可以认为是设计模式中的工厂方法, 就是你提供一个方法, 该方法返回一个对象的实例, 对于 AngularJS 的 factory 来说, 就是先定义一个对象, 给这个对象添加属性和方法, 然后返回这个对象, 例如:
var app = angular.module('MyApp', []);
app.factory('MyFactory', function() {
// define result object of factory.
var result = {};
// add some property and method to the object
result.greeting = 'Hello from factory.';
最后 controller 拿到的就是&result&对象,
相当于下面的代码:
var factoryResult = MyFactory();
所谓的 factory 就是这么简单。
service 通过&new&运算符进行实例化,
可以认为是一个类型, 只要把属性和方法添加到&this&对象上即可,
不用显式返回什么对象, 比如下面的代码:
app.service('MyService', function() {
this.greeting = 'Hello from service';
controller 拿到的对象就是上面代码中&this&指向的对象,
相当于下面的代码:
var serviceObj = new MyService();
与 factory 和 service 稍有不同的是, provider 必须提供一个&$get&方法,&$get&方法和
factory 要求是一致的, 即: 先定义一个对象, 给这个对象添加属性和方法, 然后返回这个对象, 例如:
app.provider('MyProvider', function() {
this.$get = function() {
var result = {};
result.greeting = 'Hello from provider';
最后 controller 拿到的对象就是 provider 的&$get&方法返回的对象,
相当于下面的代码:
var instance = new MyProvider();
var provider = instance.$get();
使用 factory、 service 与 provider
factory、 service 与 provider 使用起来是一样的, 都是通过 AngularJS 的依赖注入使用, 比如:
// inject factory, service and provider to a controller
app.controller('TestController', ['$scope', 'MyFactory', 'MyService', 'MyProvider', function($scope, myFactory, myService, myProvider) {
$scope.greetingFromFactory = myFactory.
$scope.greetingFromService = myService.
$scope.greetingFromProvider = myProvider.
对应的 HTML 视图为:
&body ng-controller=&TestController&&
&p&greeting from factory: {{greetingFromFactory}} &/p&
&p&greeting from service: {{greetingFromService}} &/p&
&p&greeting from provider: {{greetingFromProvider}} &/p&
provider 可以在应用启动时进行配置
provider 的特殊之处就是可以在 module 启动时进行配置, 从而达到特殊的用途, 比如在上面的 provider 中可以添加一个&setName&方法,
可以在启动时调用这个方法, 进行一些额外的初始化工作:
app.provider('MyProvider', function() {
// default name is 'anonymous';
var defaultName = 'anonymous';
var name = defaultN
// setName can be called duaring module init
this.setName = function(newName) {
name = newN
this.$get = function() {
var result = {};
result.greeting = 'Hello from provider';
result.name =
result.defaultName = defaultN
})添加了&setName&方法之后,
可以 module 启动时来调用这个方法, 实现对 provider 的配置
app.config(function(MyProviderProvider) {
MyProviderProvider.setName('Angularjs Provider');
});在 controller 中添加显示 provider 的这些信息:
app.controller('TestController', ['$scope', 'MyFactory', 'MyService', 'MyProvider', function($scope, myFactory, myService, myProvider) {
$scope.greetingFromFactory = myFactory.
$scope.greetingFromService = myService.
$scope.greetingFromProvider = myProvider.
$scope.defaultName = myProvider.defaultN
$scope.name = myProvider.name
对应的 HTML 视图也调整一下
&body ng-controller=&TestController&&
&p&greeting from factory: {{greetingFromFactory}} &/p&
&p&greeting from service: {{greetingFromService}}&/p&
&p&greeting from provider: {{greetingFromProvider}} &/p&
&p&defaultName: {{defaultName}}, config to: {{name}} &/p&
最后程序运行截图如下:
&&相关文章推荐
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:125872次
积分:1746
积分:1746
排名:千里之外
原创:47篇
转载:72篇
(1)(6)(4)(2)(4)(5)(5)(15)(8)(3)(3)(4)(4)(2)(5)(2)(4)(6)(23)(13)30982人阅读
AngularJS: Factory vs Service vs Provider
When you first get started with Angular, you’ll naturally find yourself flooding your controllers and scopes with unnecessary logic. It’s important to realize early on that your controller meaning, most of the business logic and persistent
data in your application should be taken care of or stored in a service. I see a few questions a day on Stack Overflow regarding someone trying to have persistent data in his or her controller. That’s just not the purpose of a controller. For memory purposes,
controllers are instantiated only when they are needed and discarded when they are not. Because of this, every time you switch a route or reload a page, Angular cleans up the current controller. Services however provide a means for keeping data around for
the lifetime of an application while they also can be used across different controllers in a consistent manner.
Angular provides us with three ways to create and register our own service.
1) Factory
2) Service
3) Provider
1) When you’re using a&Factory&you create an object, add properties to it, then return that same object. When you pass this service into your
controller, those properties on the object will now be available in that controller through your factory.
2) When you’re using&Service, it’s instantiated with the ‘new’ keyword. Because of that, you’ll add properties to ‘this’ and the service will
return ‘this’. When you pass the service into your controller, those properties on ‘this’ will now be available on that controller through your service.
3)&Providers&are the only service you can pass into your .config() function. Use a provider when you want to provide module-wide configuration
for your service object before making it available.
In order to extensively show the difference between a Factory, Service, and Provider, we’re going to build the same service in three separate ways. The services are going to utilize the iTunes API as well as promises with $q.
1) Factory
Factories are the most popular way to create and configure a service. There’s really not much more than what the TL;DR said. You just create an object, add properties to it, then return that same object. Then when you pass the factory into your controller,
those properties on the object will now be available in that controller through your factory. A more extensive example is below.
First we create an object, then return that object like so.
Now whatever properties we attach to ‘service’ will be available to us when we pass ‘myFactory’ into our controller.
Now let’s add some ‘private’ variables to our callback function. These won’t be directly accessible from the controller, but we will eventually set up some getter/setter methods on ‘service’ to be able to alter these ‘private’ variables when needed.
Here you’ll notice we’re not attaching those variables/function to ‘service’. We’re simply creating them in order to either use or modify them later.
& & & & baseUrl&is the base URL that the iTunes API requires
& & & & _artist&is the artist we wish to lookup
& & & & _finalUrl&is the final and fully built URL to which we’ll make the call to iTunes
& & & & makeUrl&is a function that will create and return our iTunes friendly URL.
Now that our helper/private variables and function are in place, let’s add some properties to the ‘service’ object. Whatever we put on ‘service’ we’ll be able to directly use in whichever controller we pass ‘myFactory’ into.
We are going to create setArtist and getArtist methods that simply return or set the artist. We are also going to create a method that will call the iTunes API with our created URL. This method is going to return a promise that will fulfill once the data has
come back from the iTunes API. If you haven’t had much experience using promises in Angular, I highly recommend doing a deep dive on them.
& & & & & setArtist&accepts an artist and allows you to set the artist
& & & & &&getArtist&returns
the artist
& & & & &&callItunes&first
calls makeUrl() in order to build the URL we’ll use with our $http request. Then it sets up a promise object, makes an $http request with our final url, then because $http returns a promise, we are able to call .success or .error after our request. We then
resolve our promise with the iTunes data, or we reject it with a message saying ‘There was an error’.
Now our factory is complete. We are now able to inject ‘myFactory’ into any controller and we’ll then be able to call our methods that we attached to our service object (setArtist, getArtist, and callItunes).
In the controller above we’re injecting in the ‘myFactory’ service. We then set properties on our $scope object that are coming from data from ‘myFactory’. The only tricky code above is if you’ve never dealt with promises before. Because callItunes is returning
a promise, we are able to use the .then() method and only set $scope.data.artistData once our promise is fulfilled with the iTunes data. You’ll notice our controller is very ‘thin’. All of our logic and persistent data is located in our service, not in our
controller.
2) Service
Perhaps the biggest thing to know when dealing with creating a Service is that &that it’s instantiated with the ‘new’ keyword. For you JavaScript gurus this should give you a big hint into the nature of the code. For those of &you with a limited background
in JavaScript or for those who aren’t too familiar with what the ‘new’ keyword actually does, let’s review some JavaScript fundamentals that will eventually help us in understanding the nature of a Service.
To really see the changes that occur when you invoke a function with the ‘new’ keyword, let’s create a function and invoke it with the ‘new’ keyword, then let’s show what the interpreter does when it sees the ‘new’ keyword. The end results will both be the
First let’s create our Constructor.
This is a typical JavaScript constructor function. Now whenever we invoke the Person function using the ‘new’ keyword, ‘this’ will be bound to the newly created object.
Now let’s add a method onto our Person’s prototype so it will be available on every instance of our Person ‘class’.
Now, because we put the sayName function on the prototype, every instance of Person will be able to call the sayName function in order alert that instance’s name.
Now that we have our Person constructor function and our sayName function on its prototype, let’s actually create an instance of Person then call the sayName function.
So all together the code for creating a Person constructor, adding a function to it’s prototype, creating a Person instance, and then calling the function on its prototype looks like this.
Now let’s look at what actually is happening when you use the ‘new’ keyword in JavaScript. First thing you should notice is that after using ‘new’ in our example, we’re able to call a method (sayName) on ‘tyler’ just as if it were an object – that’s because
it is. So first, we know that our Person constructor is returning an object, whether we can see that in the code or not. Second, we know that because our sayName function is located on the prototype and not directly on the Person instance, the object that
the Person function is returning must be delegating to its prototype on failed lookups. In more simple terms, when we call tyler.sayName() the interpreter says “OK, I’m going to look on the ‘tyler’ object we just created, locate the sayName function, then
call it. Wait a minute, I don’t see it here – all I see is name and age, let me check the prototype. Yup, looks like it’s on the prototype, let me call it.”.
Below is code for how you can think about what the ‘new’ keyword is actually doing in JavaScript. It’s basically a code example of the above paragraph. I’ve put the ‘interpreter view’ or the way the interpreter sees the code inside of notes.
Now having this knowledge of what the ‘new’ keyword really does in JavaScript, creating a Service in Angular should be easier to understand now.
The biggest thing to understand when creating a Service is knowing that Services are instantiated with the ‘new’ keyword. Combining that knowledge with our examples above, you should now recognize that you’ll be attaching your properties and methods directly
to ‘this’ which will then be returned from the Service itself. Let’s take a look at this in action.
Unlike what we originally did with the Factory example, we don’t need to create an object then return that object because, like mentioned many times before, we used the ‘new’ keyword so the interpreter will create that object, have it delegate to it’s prototype,
then return it for us without us having to do the work.
First things first, let’s create our ‘private’ and helper function. This should look very familiar since we did the exact same thing with our factory. I won’t explain what each line does here because I did that in the factory example, if you’re confused, re-read
the factory example.
Now, we’ll attach all of our methods that will be available in our controller to ‘this’.
Now just like in our factory, setArtist, getArtist, and callItunes will be available in whichever controller we pass myService into. Here’s the myService controller (which is almost exactly the same as our factory controller).
Like I mentioned before, once you really understand what ‘new’ does, Services are almost identical to factories in Angular.
3) Provider
The biggest thing to remember about Providers is that they’re the only service that you can pass into the app.config portion of your application. This is of huge importance if you’re needing to alter some portion of your service object before it’s available
everywhere else in your application. Although very similar to Services/Factories, there are a few differences which we’ll discuss.
First we set up our Provider in a similar way we did with our Service and Factory. The variables below are our ‘private’ and helper function.
*Again if any portion of the above code is confusing, check out the Factory section where I explain what it all does it greater details.
You can think of Providers as having three sections. The first section is the ‘private’ variables/functions that will be modified/set later (shown above). The second&section is the variables/functions that will be available in your app.config function and are
therefore available to alter before they’re available anywhere else (also shown above). It’s important to note that those variables need to be attached to the ‘this’ keyword. In our example, only ‘thingFromConfig’ will be available to alter in the app.config.&The
third&section (shown below) is all the variables/functions that will be available in your controller when you pass in the ‘myProvider’ service into that specific controller.
When creating a service with Provider, the only properties/methods that will be available in your controller are those properties/methods which are returned from the $get() function. The code below puts $get on ‘this’ (which we know will eventually be returned
from that function). Now, that $get function returns all the methods/properties we want to be available in the controller. Here’s a code example.
Now the full Provider code looks like this
Now just like in our factory and Service, setArtist, getArtist, and callItunes will be available in whichever controller we pass myProvider into. Here’s the myProvider controller (which is almost exactly the same as our factory/Service controller).
As mentioned before, the whole point of creating a service with Provider is to be able to alter some variables through the app.config function before the final object is passed to the rest of the application. Let’s see an example of that.
Now you can see how ‘thingFromConfig’ is as empty string in our provider, but when that shows up in the DOM, it will be ‘This sentence was set…’.
Thank you for reading and I hoped this helped you to be able to discern the difference between Factory, Service, and Provider in Angular.
*To see the full code example and see the code in action, feel free to fork my repo at&
&&相关文章推荐
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:466436次
积分:6444
积分:6444
排名:第3744名
原创:226篇
转载:152篇
评论:40条
(1)(1)(1)(1)(7)(12)(5)(2)(1)(5)(5)(10)(1)(4)(2)(2)(1)(9)(5)(4)(2)(6)(11)(10)(1)(13)(11)(5)(18)(11)(17)(8)(21)(19)(17)(2)(6)(4)(2)(4)(1)(13)(4)(18)(3)(5)(6)(5)(3)(6)(3)(4)(1)(1)(38)}

我要回帖

更多关于 特等座和一等座区别 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信