Understanding Angular Services

Understanding Angular Services

What are Angular Services?

Angular services are singletons objects or functions that carry out specific tasks common to web apps. Angular has a number of built in services, such as the $http service, which provides access to the browser'sXMLHttpRequest object for making requests to a server. Like other core Angular variables and identifiers, the built-in services always start with $ (such as $http mentioned above). You can also create your own custom services.

Using a Service

To use an Angular service, you identify it as a dependency for the component (controller, service, filter or directive) that depends on the service. Angular's dependency injection subsystem takes care of the rest. The Angular injector subsystem is in charge of service instantiation, resolution of dependencies, and provision of dependencies to components as requested.

Angular injects dependencies using "constructor" injection. The dependency is passed to the component's factory/constructor function. Because JavaScript is a dynamically typed language, Angular's dependency injection subsystem cannot use static types to identify service dependencies. For this reason a component must, explicitly, define its dependencies by using one of the injection annotation methods. For example, by providing a $inject property:

    var MyController = function($location) { ... };
    MyController.$inject = ['$location'];
    myModule.controller('MyController', MyController);

Or by providing an "inline" injection annotation:

    var myService = function($http) { ... };
    myModule.factory('myService', ['$http', myService]);

Defining a Service

Application developers are free to define their own services by registering their name, and service factory function, in Angular modules.

The purpose of the service factory function is to generate the single object, or function, that represents the service to the rest of the application. That object, or function, will then be injected into any component (controller, service, filter or directive) that specifies a dependency on the service.

Angular factory functions are executed lazily. That is, they are only executed when needed to satisfy a dependency, and are then executed exactly once for each service. Everything that is dependent on this service gets a reference to the single instance generated by the service factory.

Related Topics

Related API


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值