Understanding Angular Services

Angular服务作为单例对象或函数,执行特定任务,如$http服务提供访问浏览器的XMLHttpRequest对象的功能。开发者可以定义自己的服务,并通过依赖注入系统使用这些服务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值