未加星标

Understanding Factories, Services, and Providers in Angular

字体大小 | |
[前端(javascript) 所属分类 前端(javascript) | 发布者 店小二04 | 时间 2017 | 作者 红领巾 ] 0人收藏点击收藏

Understanding Factories, Services, and Providers in Angular

ByBruce Park

PostedFebruary 14, 2017

InBlogPost, Fair Job Offer Project , javascript

Understanding Factories, Services, and Providers in Angular In Implementing the Fair Offer Project

When I first started working with Angular 1.4.x, one of the concepts that confused me was the notion of factories, services, and providers.


Understanding Factories, Services, and Providers in Angular

My layman’s understanding of was that you can return objects and primitives from a function. By primitives, I mean things like numbers or strings.

Factories, services, and providers are concepts created specifically for the Angular framework created by Google, so I had to start researching them online.

I primarily looked at the Angular documentation and this post by Tyler McGinnis which gives a nice overview.

So what follows is my layman’s understanding of these basic concepts in Angular.

The general idea

To begin, Services, Factories, and Providers can be thought of as “Singleton” objects. A Singleton a singular reference to an object or function. The only exception to this is if a Factory returns a value. In this case, you get a value but not an object reference.

What is a Service?

The one point every blog post makes about services is that a service is instantiated with the new keyword behind the scenes. You won’t actually use the new keyword in your code as Angular does it for you.

In addition, you can add properties and methods on the this object.

Finally, the other important detail is that a Service is a special case of a Factory. I describe factories further in this post.

To give you a concrete example below is some code:

var CustomCalcService = angular.module('CustomCalcService', []) .service('CustomCalc', function () { this.doubleIt = function (a) { return 2*a }; }); var customCalcApp = angular.module('customCalcApp', ['CustomCalcService']); customCalcApp.controller('customCalcController', function ($scope, CustomCalc) { $scope.finddoubleIt = function () { $scope.answer = CustomCalc.doubleIt($scope.number); } }); What is a Factory?

A factory is an object that you can add properties and utilize in your controllers. You can think of it as a function with an exposed public API .

The other important detail to note about a Factory is that it is a special case of a Provider (more on Providers later on in this post).

To give you a more concrete example here is some altered code I used in a recent side project.

The code creates a factory called AuthFactory .

var fairOfferApp = angular.module('fairOfferApp.fair_offer', ['LocalStorageModule', 'ui.bootstrap', 'ui.router', 'templates', 'restangular']); fairOfferApp.factory('AuthFactory', ['$q', '$http', '$timeout', function($q, $http, $timeout) { var _identity = undefined, _authenticated = false; return { isIdentityResolved: function() { _identity = true; //this is a dummy value for the purposes of this exercise return _identity; } } //end function($q, $http, $timeout) ]); //end fairOfferApp.factory...

Finally, here is an example of how you can reference the factory in your controller:

fairOfferApp.controller('loginCtrl', ['$scope', '$location', 'localStorageService', 'Restangular', 'AuthFactory', function($scope, $location, localStorageService, Restangular, AuthFactory) { console.log(AuthFactory.isIdentityResolved()); }]); What is a Provider?

Believe it or not, services and factories are “syntactic sugar on top of a provider recipe” according to the Angular documentation .

The first main differentiating feature of a Provider is that it implements a $get method. The other differentiating feature is that it’s the only type of “object” you can pass into the app.config portion of an Angular application.

var customCalcApp = angular.module('customCalcApp', []); customCalcApp.provider("calcProvider", function() { this.$get = function() { console.log("calcProvider function $get() called."); return "my provider value"; }; }); customCalcApp.controller("customCalcController", function(calcProvider) { console.log("customCalcController - calcProvider: " + calcProvider); //console output: //customCalcController - calcProvider: my provider value }); How do you know when to Use a Service, Factory, or Provider?

The best answer I found came from the aforementioned StackOverflow post which I will quote verbatim below:

Factory: Thevalueyouareprovidingneedsto becalculatedbasedonotherdata. Service: Youarereturninganobject withmethods. Provider: Youwantto beableto configure, duringtheconfigphase, theobject thatis goingto becreatedbeforeit’s created. Use theProvidermostlyin theappconfig, beforetheapphasfullyinitialized.

Personally, when just starting out with Angular, I found it easier to use a Service or Factory. I usually try to get something working and then make refinements as I learn more.

Summary

You can think of Services, Factories, and Providers as “Singleton” class objects that are special cases of each other. Factories and Services are usually the easiest to use when you’re just getting started.

本文前端(javascript)相关术语:javascript是什么意思 javascript下载 javascript权威指南 javascript基础教程 javascript 正则表达式 javascript设计模式 javascript高级程序设计 精通javascript javascript教程

主题: Java
分页:12
转载请注明
本文标题:Understanding Factories, Services, and Providers in Angular
本站链接:http://www.codesec.net/view/533763.html
分享请点击:


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 前端(javascript) | 评论(0) | 阅读(82)