dferrandizmont
12/16/2018 - 10:37 AM

[Services] #agular

[Services] #angular

Services

Use service for any Class that is to be mapped into the dependency injector.

Do not use a service for a method (use a Class instead).

Services are implemented as a Class and should be PascalCase. Angular will instantiate once only and inject the same instance in all cases. The dependency is therefore camelCase since it is an instance and should not be new'd. For example:

angular.module(...).service('myService', MyService);

It is prudent to bind() public members (accessors and functions) to ensure that their this reference is not lost.

In javascript instance methods can easily loose their this reference. We can leverage Function.bind() method can to bind all functions and accessors of a given object.

constructor

Injection is available in the constructor only. This must be annotated with the @ngInject doctag.

Firstly bind the instance.

Initialise any private properties.

functions, accessors, properties

Public properties (i.e. variables) are not permitted. Use accessors, meaning getter and/or setter methods.

The function keyword is not needed.

The 'use strict' statement is not needed.

private properties

Private properties should have the same name as any public property that it shadows. A trailing underscore is required per google javascript style.