Services (Service)

Source: Internet
Author: User

Services (Service)

Angular Services is substitutable objects that is wired together using Dependency injection (DI). You can use the services to organize and share code across your app.

Angular services are:

    • Lazily Instantiated-angular only instantiates a service if an application component depends on it.

    • Singletons-each component dependent on a service gets a reference to the single instance generated by the service factor Y.

Angular offers several useful services (like $http), but for the most applications you'll also want to create your own.

The angular service is a replaceable object that is strung together using dependency injection. You can use the service to organize and share code for your app.

Angular's services have these features:

    • Lazy initialization: Angular is only initialized when a component in the app relies on it.

    • Singleton: Each component that relies on a service obtains only one reference for that service, which points to the instance that the Service factory created (singleton)

Note:like Other core Angular identifiers, built-in services always start with $ (e.g. $http).

Using a service (with services)

To use an Angular service, you add it as a dependency for the component (Controller, service, filter or directive) that de Pends on the service. Angular ' s Dependency Injection takes care of the rest.

How do I use the service? Add a dependency on your component to it. The rest of the work is given to angular's dependency injection mechanism.

Index.html:

1 <DivID= "simple"Ng-controller= "Mycontroller" >2     <P>Let's try this simple notify service, injected into the controller ...</P>3     <inputNg-init= "message= ' Test '"Ng-model= "message" >4     <ButtonNg-click= "callnotify (message);" >NOTIFY</Button>5     <P>(You have to click 3 times to see a alert)</P>6 </Div>

Script.js:

1 Angular.2Module (' Myservicemodule ' , []).3Controller (' Mycontroller ', [' $scope ', ' Notify ',function($scope, notify) {4$scope. Callnotify =function(msg) {5 Notify (msg);6     };7 }]).8Factory (' Notify ', [' $window ',function(Win) {9     varMsgs = [];Ten     return function(msg) { One msgs. push (msg); A         if(msgs. Length = = 3 ) { -Win. Alert (msgs. Join ("\ n") )); -Msgs = []; the         } -     }; -}]);

Creating Services (Create service)

Application developers is free to define their own services by registering the service ' s name and service factory Functio N, with an Angular module.

The Service factory function generates the single object or function this represents the service to the rest of the Applic ation. The object or function returned by the service was injected into any component (Controller, service, filter or directive) t Hat specifies a dependency on the service.

Developers can define their own services by registering the name of the service and the factory method into a angular module.

The Service factory method is the singleton object or method that is used to create the service. The created service (either an object or a method) is injected into the component that relies on it.

Registering Services (registration Service)

Services is registered to modules via the Module API. Typically the Module factory API to register a service:

1 var mymodule = angular. Module (' MyModule ' , []); 2 function () {3     var shinynewserviceinstance; 4     // Factory function body that constructs shinynewserviceinstance 5     return shinynewserviceinstance; 6 });

Note that the registering a service instance, but rather a factory function that would create this instance when CA Lled.

The service can be registered through the module API. In general, use the module's factory API to register.

Note that you are not registering an instance of the service, but rather a factory function that can create a service instance.

Dependencies (Dependencies)

Services can have their own dependencies. Just like declaring dependencies in a controller, you declare dependencies by specifying them in the service's factory fun Ction signature. The example module below has both services, with various dependencies:

The service can also have its own dependencies. Similar to declaring dependencies in a controller, we can also use a similar notation when registering a service to declare a dependency on a service.

1 varBatchmodule = angular. Module (' Batchmodule ' , []);2 /**3 * the ' batchlog ' service allows for messages to being queued in memory and flushed4 * to the console.log every-seconds.5 *6 * @param {*} message message to be logged.7 */8Batchmodule. Factory (' Batchlog ', [' $internal ', ' $log ',function($internal, $log) {9     varMessageQueue = [];Ten     functionlog () { One         if(messageQueue. Length) { A$log. Log (' Batchlog message: ', messageQueue); -MessageQueue = []; -         } the     } -     //Start periodic checking -$internal (log, 50000 ); -     return function(message) { + messageQueue. push (message); -     } + }]); A /** at * ' routetemplatemonitor ' monitors each ' $route ' , and logs the current - * Template via the ' batchlog ' service. - */ -Batchmodule. Factory (' Routetemplatemonitor ', [' $route ', ' batchlog ', ' $rootScope ' , -     function($route, Batchlog, $rootScope) { -$rootScope. $on (' $routeChangeSuccess ',function () { inBatchlog ($route. $route. Current. Template:NULL ); -         }); to}]);

In the example, note that:

    • The Batchlog service depends on the built-in $internal and $log services.

    • The Routetemplatemonitor service depends on the built-in $route service and our custom Batchlog service.

    • Both services use the array notation to declare their dependencies.

    • The order of identifiers in the array was the same as the order of argument names in the factory function.

In the above example, note the following:

    • Batchlog service relies on built-in services $internal and $log

    • The Routetemplatemonitor service relies on built-in $route services and also relies on our batchlog services

    • Both of these custom services are dependent relationships declared using array notation

    • The order of the dependency injection and the parameter order of the factory function must be

Registering a service with $provide (registered with $provide)

You can also register services via the $provide service inside of a module ' s config function:

function ($provide) {   function  () {        var  shinynewserviceinstance;         // Factory function body that constructs shinynewserviceinstance        return ( shinynewserviceinstance;    });}]);

This technique was often used in the unit tests to the mock out a service ' s dependencies.

Of course, you can also use $provide to register the service in the Config method of the module.

However, this technique is often used in unit tests to simulate service dependencies.



Services (Service)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.