angular服务
angular创建服务的五种方式:
factory()
factory()方法是创建和配置服务的最快捷方式。factory()函数可以接受两个参数。
name(字符串)
需要注册的服务名。
getFn(函数)
这个函数会在AngularJS创建服务实例时被调用。
- angular.module('myApp')
- .factory('myService', function() {
- return {
- 'username': 'auser'
- };
- });
因为服务是单例对象,getFn在应用的生命周期内只会被调用一次。同其他AngularJS的服务
一样,在定义服务时,getFn可以接受一个包含可被注入对象的数组或函数。
getFn函数可以返回简单类型、函数乃至对象等任意类型的数据(同value()函数类似)。
- angular.module('myApp')
- .factory('githubService', ['$http', function($http) {
- return {
- getUserEvents: function(username) {
- // ...
- }
- };
- }]);
service()
使用service()可以注册一个支持构造函数的服务,它允许我们为服务对象注册一个构造
函数。
service()方法接受两个参数。
name(字符串)
要注册的服务名称。
constructor(函数)
构造函数,我们调用它来实例化服务对象。
service()函数会在创建实例时通过new关键字来实例化服务对象。
- var Person = function($http) {
- this.getName = function() {
- return $http({ method: 'GET', url: '/api/user'});
- };
- };
- angular.service('personService', Person);
constant()
可以将一个已经存在的变量值注册为服务,并将其注入到应用的其他部分当中。例如,假设
我们需要给后端服务一个apiKey,可以用constant()将其当作常量保存下来。
constant()函数可以接受两个参数。
name(字符串)
需要注册的常量的名字。
value(常量)
需要注册的常量的值(值或者对象)。
constant()方法返回一个注册后的服务实例。
- angular.module('myApp') .constant('apiKey','123123123')
这个常量服务可以像其他服务一样被注入到配置函数中:
- angular.module('myApp')
- .controller('MyController', function($scope, apiKey) {
- // 可以像上面一样用apiKey作为常量
- // 用123123123作为字符串的值
- $scope.apiKey = apiKey;
- });
value()
如果服务的$get方法返回的是一个常量,那就没要必要定义一个包含复杂功能的完整服务,
可以通过value()函数方便地注册服务。
value()方法可以接受两个参数。
name(字符串)
同样是需要注册的服务名。
value(值)
将这个值将作为可以注入的实例返回。
value()方法返回以name参数的值为名称的注册后的服务实例。
- angular.module('myApp')
- .value('apiKey','123123123');
provider()
所有服务工厂都是由$provide服务创建的,$provide服务负责在运行时初始化这些提供者。
提供者是一个具有$get()方法的对象,$injector通过调用$get方法创建服务实例。
$provider提供了数个不同的API用于创建服务,每个方法都有各自的特殊用途。
所有创建服务的方法都构建在provider方法之上。provider()方法负责在$providerCache
中注册服务。
从技术上说,当我们假定传入的函数就是$get()时,factory()函数就是用provider()方法
注册服务的简略形式。
下面两种方法的作用完全一样,并且会创建同一个服务。
- angular.module('myApp')
- .factory('myService', function() {
- return {
- 'username': 'auser'
- };
- })
- // 这与上面工厂的用法等价
- .provider('myService', {
- $get: function() {
- return {
- 'username': 'auser'
- };
- }
- });
是否可以一直使用.factory()方法来代替.provider()呢?
答案取决于是否需要用AngularJS的.config()函数来对.provider()方法返回的服务进行额
外的扩展配置。同其他创建服务的方法不同,config()方法可以被注入特殊的参数。
比如我们希望在应用启动前配置githubService的URL:
- // 使用`.provider`注册该服务
- angular.module('myApp', [])
- .provider('githubService', function($http) {
- // 默认的,私有状态
- var githubUrl = 'https://github.com'
- setGithubUrl: function(url) {
- // 通过.config改变默认属性
- if (url) { githubUrl = url }
- },
- method: JSONP, // 如果需要,可以重写
- $get: function($http) {
- self = this;
- return $http({ method: self.method, url: githubUrl + '/events'});
- }
- });
通过使用.provider()方法,可以在多个应用使用同一个服务时获得更强的扩展性,特别是
在不同应用或开源社区之间共享服务时。
在上面的例子中,provider()方法在文本githubService后添加Provider生成了一个新的提
供者,githubServiceProvider可以被注入到config()函数中。
- angular.module('myApp', [])
- .config(function(githubServiceProvider) {
- githubServiceProvider.setGithubUrl("git@github.com");
- });
如果希望在config()函数中可以对服务进行配置,必须用provider()来定义服务。
provider()方法为服务注册提供者。可以接受两个参数。
name(字符串)
name参数在providerCache中是注册的名字。name+Provider会成为服务的提供者。同时name
也是服务实例的名字。
例如,如果定义了一个githubService,那它的提供者就是githubServiceProvider。
aProvider(对象/函数/数组)
aProvider可以是多种形式。
如果aProvider是函数,那么它会通过依赖注入被调用,并且负责通过$get方法返回一个
对象。
如果aProvider是数组,会被当做一个带有行内依赖注入声明的函数来处理。数组的最后一
个元素应该是函数,可以返回一个带有$get方法的对象。
如果aProvider是对象,它应该带有$get方法。
provider()函数返回一个已经注册的提供者实例。
直接使用provider() API是最原始的创建服务的方法:
- // 在模块对象上直接创建provider的例子
- angular.module('myApp', [])
- .provider('UserService', {
- favoriteColor: null,
- setFavoriteColor: function(newColor) {
- this.favoriteColor = newColor;
- },
- // $get函数可以接受injectables
- $get: function($http) {
- return {
- 'name': 'Ari',
- getFavoriteColor: function() {
- return this.favoriteColor || 'unknown';
- }
- };
- }
- });
用这个方法创建服务,必须返回一个定义有$get()函数的对象,否则会导致错误。
- // Get the injector
- var injector = angular.injector(['myApp']); // Invoke our service
- injector.invoke(
- ['UserService', function(UserService) {
- // UserService returns
- // {
- // 'name': 'Ari',
- // getFavoriteColor: function() {}
- // }
- }]);
.provider()是非常强大的,可以让我们在不同的应用中共享服务。
了解constant()和value()方法对于创建服务也是非常重要的。
angular服务的更多相关文章
- angular服务二
angular服务 $http 实现客户端与服务器端异步请求 get方式 test.html <!DOCTYPE html> <html lang="en"> ...
- angular服务一
angular服务 [$apply()] jquery内数据绑定 要用$apply(),不然不能在js内通过angular绑定数据 <!DOCTYPE html> <html lan ...
- angular 服务 service factory provider constant value
angular服务 服务是对公共代码的抽象,由于依赖注入的要求,服务都是单例的,这样我们才能到处注入它们,而不用去管理它们的生命周期. angular的服务有以下几种类型: 常量(Constant): ...
- 理解 Angular 服务
理解 Angular 服务 本文写于 2021 年 3 月 29 日 理解 Angular 服务 什么是服务 服务写法 原理简述 提供服务 1. 在服务中注册 2. 在 module 中注册 3. 在 ...
- angular 服务
在Angular里面,services作为单例对象在需要到的时候被创建,只有在应用生命周期结束的时候(关闭浏览器)才会被清除.而controllers在不需要的时候就会被销毁了.服务用于在控制器之间进 ...
- Angular服务的5种创建方式
config配置块 Angular应用的运行主要分为两部分:app.config()和app.run(),config是你设置任何的provider的阶段,从而使应用可以使用正确的服务,需要注意的是在 ...
- Angular 服务的简单使用
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- angular 服务之间依赖注入
import { Injectable } from '@angular/core'; @Injectable() export class LoggerServiceService { constr ...
- Angular定义服务-Learn By Doing
1.服务(Service)介绍 Angular services are substitutable objects that are wired together using dependency ...
随机推荐
- IO流入门-第七章-BufferedReader
BufferedReader基本用法和方法示例 /* 字节 BufferedInputStream BufferedOutputStream 字符 BufferedReader:带有缓冲区的字符输入流 ...
- shell判断文件/目录是否存在
https://www.cnblogs.com/37yan/p/6962563.html caution!!! if should be end with fi caution!!! there sh ...
- 汉澳sinox2014没有黑屏,一个能够依靠的安全避风港
首先汉澳sinox2014没有验证server,根本就没办法区分正版和盗版 其次汉澳sinox2014安装也没有系列号cdkey等东西,直接安装无干扰 最后汉澳sinox2014不会有黑屏这样的东西. ...
- Ubuntu学习笔记1-基本部分
Vim相当于vi的升级版 Find p*.txt支持查找通配符 Echo 回显命令 echo hello >1.txt 追加命令,不覆盖 echo hello >1.txt 覆盖命 ...
- 吴超老师课程--HBASE的Java_API
public static void main(String[] args) throws IOException { String tableName="hbase_tb"; S ...
- git-bash使用ctrl C无法终止nodemon的执行
原因: git的bug 解决:git版本降级为2.10.0好了
- C#求百分比
public string integralpercentage; integralpercentage = ((double)user.Credits / integralmax).ToString ...
- 【leetcode刷题笔记】Rotate Image
You are given an n x n 2D matrix representing an image. Rotate the image by 90 degrees (clockwise). ...
- shell脚本小示例
求1-100自然数的和: 法一:for循环 #!/bin/bash # declare -i sum=0 for ((i=0;i<=100;i++));do let sum+=$i done e ...
- python之模块导入和重载
模块导入和重载 模块导入通过import语句实现,但是在同一次会话中只运行一次. 若想要再次运行文件,调用imp标准库中的reload函数: >>> from imp import ...