Details about the Custom Service, Provider, Factory, and angularprovider in Angular
The background came from an interview some time ago. The interviewer looked at my Angular controller and added a variety of methods with repeated features, but patiently tell me that improving Angular code reusability requires three methods with high reusability: Service, Provider, and Factory. The following are my learning achievements:
Let's talk about Factory:
By registering. factory ('My registration name', method () and returning an object, you can introduce this method in the Controller and access this object:
Example:
<! -- Factory mode --> <div ng-controller = "theFactoryCtrl">
JS Code:
/* Factory mode. The injection parameter calls the return value of this function */app. factory ("myFactory", function () {var args = arguments; var obj = {} obj.exe c = function () {var arr = []; for (let I = 0; I <arguments. length; I ++) {arr. push (arguments [I]);} return arr;} return obj;}) app. controller ("theFactoryCtrl", function ($ scope, myFactory) {$ scope. names = myFactory.exe c ("Zhang San's song", "Zhao Si's Dance", "Lao Wang's six thieves ");})
Effect:
Service:
The constructor is used in the service, and is introduced in the Controller in the new way. Therefore, you can call the properties defined in the service.
HTML:
<! -- Service mode --> <div ng-controller = "theServiceCtrl">
JS:
App. controller ("theServiceCtrl", function ($ scope, myService) {$ scope. prop = myService. prop ("Haha"); $ scope. num = myService. num;})/* the Service is new, so you can directly call the properties */app. service ("myService", function () {this. num = Math. floor (Math. random () * 10); // random number from 0 to 10 this. prop = function (arg) {return arg ;};})
Effect:
Provider:
If you want to configure the service before creating the service, you need provider, because provider can define config and access config in $ get
HTML:
<! -- Provider mode --> <div ng-controller = "theProviderCtrl">
JS:
/* Use the $ get method to associate the corresponding config */app. provider ("myProvider", function () {this. $ get = function () {return {name: "Zhu ziming", squad: "386 brigade independent mission", role: this. roleSet }})/* name must comply with the specifications: xxxxxxProvider */app. config (function (myProviderProvider) {myProviderProvider. roleSet = "Security Officer"}) app. controller ("theProviderCtrl", function ($ scope, myProvider) {$ scope.info = {name: myProvider. name, squad: myProvider. squad, role: myProvider. role }})
Effect:
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.