injection de dépendance - AngularJS: Service vs fournisseur vs usine

Mots clés : angularjsdependency-injectionangularjs-serviceangularjs-factoryangularjs-providerangularjs

meilleur 4 Réponses injection de dépendance - AngularJS: Service vs fournisseur vs usine

vote vote

96

provide.value('a', 123);  function Controller(a) {   expect(a).toEqual(123); } 
provide.factory('b', function(a) {   return a*2; });  function Controller(b) {   expect(b).toEqual(246); } 
function Greeter(a) {   this.greet = function() {     return 'Hello ' + a;   } } 
provide.factory('greeter', function(a) {   return new Greeter(a); }); 
function Controller(greeter) {   expect(greeter instanceof Greeter).toBe(true);   expect(greeter.greet()).toEqual('Hello 123'); } 
provide.provider('greeter2', function() {   var salutation = 'Hello';   this.setSalutation = function(s) {     salutation = s;   }    function Greeter(a) {     this.greet = function() {       return salutation + ' ' + a;     }   }    this.$get = function(a) {     return new Greeter(a);   }; }); 
angular.module('abc', []).config(function(greeter2Provider) {   greeter2Provider.setSalutation('Halo'); });  function Controller(greeter2) {   expect(greeter2.greet()).toEqual('Halo 123'); } 
provider.service = function(name, Class) {   provider.provide(name, function() {     this.$get = function($injector) {       return $injector.instantiate(Class);     };   }); }  provider.factory = function(name, factory) {   provider.provide(name, function() {     this.$get = function($injector) {       return $injector.invoke(factory);     };   }); }  provider.value = function(name, value) {   provider.factory(name, function() {     return value;   }); }; 
vote vote

89

var myApp = angular.module('myApp', []);    //service style, probably the simplest one  myApp.service('helloWorldFromService', function() {      this.sayHello = function() {          return "Hello, World!";      };  });    //factory style, more involved but more sophisticated  myApp.factory('helloWorldFromFactory', function() {      return {          sayHello: function() {              return "Hello, World!";          }      };  });        //provider style, full blown, configurable version       myApp.provider('helloWorld', function() {        this.name = 'Default';        this.$get = function() {          var name = this.name;          return {              sayHello: function() {                  return "Hello, " + name + "!";              }          }      };        this.setName = function(name) {          this.name = name;      };  });    //hey, we can configure a provider!              myApp.config(function(helloWorldProvider){      helloWorldProvider.setName('World');  });              function MyCtrl($scope, helloWorld, helloWorldFromFactory, helloWorldFromService) {            $scope.hellos = [          helloWorld.sayHello(),          helloWorldFromFactory.sayHello(),          helloWorldFromService.sayHello()];  }
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>  <body ng-app="myApp">  <div ng-controller="MyCtrl">      {{hellos}}  </div>  </body>
vote vote

76

app.controller(‘myFactoryCtrl’, function($scope, myFactory){   $scope.artist = myFactory.getArtist(); });  app.factory(‘myFactory’, function(){   var _artist = ‘Shakira’;   var service = {};    service.getArtist = function(){     return _artist;   }    return service; }); 
app.controller(‘myServiceCtrl’, function($scope, myService){   $scope.artist = myService.getArtist(); });  app.service(‘myService’, function(){   var _artist = ‘Nelly’;   this.getArtist = function(){     return _artist;   } }); 
app.controller(‘myProvider’, function($scope, myProvider){   $scope.artist = myProvider.getArtist();   $scope.data.thingFromConfig = myProvider.thingOnConfig; });  app.provider(‘myProvider’, function(){  //Only the next two lines are available in the app.config()  this._artist = ‘’;  this.thingFromConfig = ‘’;   this.$get = function(){     var that = this;     return {       getArtist: function(){         return that._artist;       },       thingOnConfig: that.thingFromConfig     }   } });  app.config(function(myProviderProvider){   myProviderProvider.thingFromConfig = ‘This was set in config’; }); 
app.factory(‘myFactory’, function(){   var service = {};   return service; }); 
app.factory(‘myFactory’, function($http, $q){   var service = {};   var baseUrl = ‘https://itunes.apple.com/search?term=’;   var _artist = ‘’;   var _finalUrl = ‘’;    var makeUrl = function(){    _artist = _artist.split(‘ ‘).join(‘+’);     _finalUrl = baseUrl + _artist + ‘&callback=JSON_CALLBACK’;     return _finalUrl   }    return service; }); 
app.factory('myFactory', function($http, $q){   var service = {};   var baseUrl = 'https://itunes.apple.com/search?term=';   var _artist = '';   var _finalUrl = '';    var makeUrl = function(){     _artist = _artist.split(' ').join('+');     _finalUrl = baseUrl + _artist + '&callback=JSON_CALLBACK'     return _finalUrl;   }    service.setArtist = function(artist){     _artist = artist;   }    service.getArtist = function(){     return _artist;   }    service.callItunes = function(){     makeUrl();     var deferred = $q.defer();     $http({       method: 'JSONP',       url: _finalUrl     }).success(function(data){       deferred.resolve(data);     }).error(function(){       deferred.reject('There was an error')     })     return deferred.promise;   }    return service; }); 
app.controller('myFactoryCtrl', function($scope, myFactory){   $scope.data = {};   $scope.updateArtist = function(){     myFactory.setArtist($scope.data.artist);   };    $scope.submitArtist = function(){     myFactory.callItunes()       .then(function(data){         $scope.data.artistData = data;       }, function(data){         alert(data);       })   } }); 
var Person = function(name, age){   this.name = name;   this.age = age; } 
Person.prototype.sayName = function(){   alert(‘My name is ‘ + this.name); } 
var tyler = new Person(‘Tyler’, 23); tyler.sayName(); //alerts ‘My name is Tyler’ 
var Person = function(name, age){   this.name = name;   this.age = age; } Person.prototype.sayName = function(){   alert(‘My name is ‘ + this.name); } var tyler = new Person(‘Tyler’, 23); tyler.sayName(); //alerts ‘My name is Tyler’ 
var Person = function(name, age){   //The below line creates an object(obj) that will delegate to the person’s prototype on failed lookups.   //var obj = Object.create(Person.prototype);    //The line directly below this sets ‘this’ to the newly created object   //this = obj;    this.name = name;   this.age = age;    //return this; } 
app.service('myService', function($http, $q){   var baseUrl = 'https://itunes.apple.com/search?term=';   var _artist = '';   var _finalUrl = '';    var makeUrl = function(){     _artist = _artist.split(' ').join('+');     _finalUrl = baseUrl + _artist + '&callback=JSON_CALLBACK'     return _finalUrl;   } }); 
app.service('myService', function($http, $q){   var baseUrl = 'https://itunes.apple.com/search?term=';   var _artist = '';   var _finalUrl = '';    var makeUrl = function(){     _artist = _artist.split(' ').join('+');     _finalUrl = baseUrl + _artist + '&callback=JSON_CALLBACK'     return _finalUrl;   }    this.setArtist = function(artist){     _artist = artist;   }    this.getArtist = function(){     return _artist;   }    this.callItunes = function(){     makeUrl();     var deferred = $q.defer();     $http({       method: 'JSONP',       url: _finalUrl     }).success(function(data){       deferred.resolve(data);     }).error(function(){       deferred.reject('There was an error')     })     return deferred.promise;   }  }); 
app.controller('myServiceCtrl', function($scope, myService){   $scope.data = {};   $scope.updateArtist = function(){     myService.setArtist($scope.data.artist);   };    $scope.submitArtist = function(){     myService.callItunes()       .then(function(data){         $scope.data.artistData = data;       }, function(data){         alert(data);       })   } }); 
app.provider('myProvider', function(){    var baseUrl = 'https://itunes.apple.com/search?term=';   var _artist = '';   var _finalUrl = '';    //Going to set this property on the config function below.   this.thingFromConfig = ‘’;    var makeUrl = function(){     _artist = _artist.split(' ').join('+');     _finalUrl = baseUrl + _artist + '&callback=JSON_CALLBACK'     return _finalUrl;   } } 
this.$get = function($http, $q){     return {       callItunes: function(){         makeUrl();         var deferred = $q.defer();         $http({           method: 'JSONP',           url: _finalUrl         }).success(function(data){           deferred.resolve(data);         }).error(function(){           deferred.reject('There was an error')         })         return deferred.promise;       },       setArtist: function(artist){         _artist = artist;       },       getArtist: function(){         return _artist;       },       thingOnConfig: this.thingFromConfig     }   } 
app.provider('myProvider', function(){   var baseUrl = 'https://itunes.apple.com/search?term=';   var _artist = '';   var _finalUrl = '';    //Going to set this property on the config function below   this.thingFromConfig = '';    var makeUrl = function(){     _artist = _artist.split(' ').join('+');     _finalUrl = baseUrl + _artist + '&callback=JSON_CALLBACK'     return _finalUrl;   }    this.$get = function($http, $q){     return {       callItunes: function(){         makeUrl();         var deferred = $q.defer();         $http({           method: 'JSONP',           url: _finalUrl         }).success(function(data){           deferred.resolve(data);         }).error(function(){           deferred.reject('There was an error')         })         return deferred.promise;       },       setArtist: function(artist){         _artist = artist;       },       getArtist: function(){         return _artist;       },       thingOnConfig: this.thingFromConfig     }   } }); 
app.controller('myProviderCtrl', function($scope, myProvider){   $scope.data = {};   $scope.updateArtist = function(){     myProvider.setArtist($scope.data.artist);   };    $scope.submitArtist = function(){     myProvider.callItunes()       .then(function(data){         $scope.data.artistData = data;       }, function(data){         alert(data);       })   }    $scope.data.thingFromConfig = myProvider.thingOnConfig; }); 
app.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'; }); 
vote vote

62

app.factory('MyFactory', function() {     var serviceObj = {};     //creating an object with methods/functions or variables     serviceObj.myFunction = function() {         //TO DO:     };     //return that object     return serviceObj; }); 
app.service('MyService', function() {     //directly binding events to this context     this.myServiceFunction = function() {         //TO DO:     }; }); 
app.provider('configurableService', function() {     var name = '';     //this method can be be available at configuration time inside app.config.     this.setName = function(newName) {         name = newName;     };     this.$get = function() {         var getName = function() {              return name;         };         return {             getName: getName //exposed object to where it gets injected.         };     }; }); 

Questions similaires