Skip to content

Instantly share code, notes, and snippets.

@dferrandizmont
Last active December 17, 2018 14:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dferrandizmont/6184bf9dba40fed48f23cb8811c9e704 to your computer and use it in GitHub Desktop.
Save dferrandizmont/6184bf9dba40fed48f23cb8811c9e704 to your computer and use it in GitHub Desktop.
[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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment