How to define a constructor in a service and factory in Angular?

I am a little familiar with angular. still in the learning process. work with ng version 1.4.8. therefore, I like to know how to define the constructor function in a service and factory.

here is one sample service. Now tell me how to define a constructor in a service or factory?

angular.module('myApp').service('helloService',function($timeout){
  this.sayHello=function(name){
    $timeout(function(){
      alert('Hello '+name);
    },2000);
  }
});

angular.module('myApp').controller('TestController',
  function(helloService){
  helloService.sayHello('AngularJS'); // Alerts Hello AngularJS
});
+4
source share
2 answers

The function you pass in .serviceis called with new, so it is already basically a constructor. This is a "constructor function", and it implicitly returns an object that is singleton:

angular.module('myApp').service('helloService',function($timeout){
  // This constructor function implicitly returns an object. It is called
  // only once by Angular to create a singleton.

  this.sayHello=function(name){
    // etc
  }
});

, .service ES6 ( ) -, , :

class HelloService {
    constructor($timeout) {
        // Called once when the singleton is created
    }

     sayHello(name) {
         // etc
     }
}

angular.module('myApp').service('helloService', HelloService);

.factory , new. , , , singleton :

angular.module('myApp').factory('helloService',function($timeout){
  // This factory function explicitly returns an object. It is called
  // only once by Angular to create a singleton.

  return {
      sayHello: function(name) {
          // etc
      }
  };
});

. @Vladimir Zdenek, "" . " , ?". , , , "".

+2

(, ) , . , .

, / factory . .

, , - ( JavaScript), factory . .

function MyFactory(myParams) {

    const Factory = {
        // Properties
        myProperty: myParams.myProperty,
        // Methods
        getMyProperty: getMyProperty
    };

    return Factory;

    function getMyProperty() {
        return Factory.myProperty;
    }

}

// usage
const myObj = MyFactory({ myProperty: 'Hello' });
+3

Source: https://habr.com/ru/post/1679055/


All Articles