AngularJS Service
讲解 AngularJS 服务的依赖注入机制、$location 与 window.location 的系统对比、$http/$timeout/$interval 内建服务,以及自定义服务注册与向过滤器注入复用。
学完这一章,你能够
- 讲解 AngularJS 服务的依赖注入机制、$location 与 window.location 的系统对比、$http/$timeout/$interval 内建服务,以及自定义服务注册与向过滤器注入复用。
什么是服务以及为何不直接使用原生全局对象
在 AngularJS 中,服务(Service)是可在整个应用内按单例复用的函数或对象。框架内建了 30 多个常用服务,如用于读取与操作当前地址的 `$location` 服务。使用内建或自定义服务时,只需将其名称作为参数声明在控制器(或其他可注入组件)中,框架的依赖注入器会自动传入实例(例如调用 `$location.absUrl()` 获取完整 URL)。
虽然浏览器本身提供 `window.location`、`window.setTimeout` 等全局对象,但在 AngularJS 应用中直接使用它们会绕过框架的生命周期监控与 `$digest` 脏检查机制,导致模型变更无法自动反映到视图,也不便于单元测试替换。使用 `$location` 等包装服务可与 `$watch`、HTML5 History API 降级及应用相对路径上下文无缝整合(详细差异见下表)。本站通过本地回环 URL `/app/index.html#!/items/42?tab=info` 实测:`$location.absUrl()` 返回完整地址,`$location.path()` 返回应用内相对路径 `"/items/42"`(而 `window.location.pathname` 返回宿主文档路径 `"/app/index.html"`),调用 `$location.path('/orders')` 时自动触发路径监听记录 `"/items/42->/orders"`。
核心内建服务:$http、$timeout 与 $interval
`$http` 是 AngularJS 最常用的异步通信服务,用于向服务器发起 HTTP 请求并处理响应数据(例如 `$http.get('welcome.htm').then(function(response) { $scope.myWelcome = response.data; })`,更完整的配置、方法与版本差异将在下一章专门展开)。本站离线通过本地回环接口 `/welcome.htm` 实测,回调正确取得响应体 `"Hello AngularJS Services"` 并写入视图。
`$timeout` 服务对应原生 `window.setTimeout`,但在回调执行完毕后会自动触发脏检查以刷新视图,并返回可取消的 Promise。本站离线实测:标题初始为 `"Hello World!"`,延时触发后自动更新为 `"How are you today?"`。
`$interval` 服务对应原生 `window.setInterval`,用于周期性轮询或时钟刷新(如每秒更新一次当前时间),并支持指定最大执行次数或通过 `$interval.cancel()` 及时清理以防内存泄漏。本站离线实测配置 3 次周期回调,计数准确递增至 `3` 后自动停止。
创建自定义服务并在控制器与过滤器中复用
通过 `app.service('hexafy', function() { this.myFunc = function(x) { return x.toString(16); }; })` 可将自定义逻辑封装为模块服务(AngularJS 会用 `new` 实例化构造函数)。之后在控制器参数列表中声明 `hexafy` 即可注入调用,本站离线实测 `hexafy.myFunc(255)` 返回十六进制字符串 `"ff"`。
自定义服务注册到模块后,不仅能注入控制器,还能注入指令、过滤器或其他服务中实现跨层复用。例如使用数组注入标注 `app.filter('myFormat', ['hexafy', function(hexafy) { return function(x) { return hexafy.myFunc(x); }; }])` 将 `hexafy` 注入过滤器,即可在 `ng-repeat="x in counts"` 中以 `{{x | myFormat}}` 批量格式化数组项。本站实测输入 `[255, 251, 200]`,页面准确渲染 `["ff", "fb", "c8"]`。
$location 服务与原生 window.location 特性对比
| 对比维度 | window.location | $location 服务 |
|---|---|---|
| 目的 | 读写当前浏览器的地址栏位置 | 读写当前浏览器的地址栏位置 |
| API | 直接暴露可读写的原生属性对象 | 暴露链式读写器方法(如 path()、absUrl()) |
| 生命周期整合 | 否,改动不自动进入 $digest 脏检查 | 是,可接入应用生命周期并与 $watch 联动 |
| HTML5 History 整合 | 否,需手动处理兼容性差异 | 是,支持 HTML5 模式并对旧浏览器优雅降级为 Hash |
| 应用路径上下文 | 否,pathname 返回含宿主目录的完整路径(如 /app/index.html) | 是,$location.path() 返回相对于应用根的路径(如 /items/42) |
验证 $location 路径监听、$http/$timeout/$interval 及自定义 hexafy 服务注入过滤器
"""Offline Playwright Chromium lab for AngularJS Ch 09 (services)."""
import http.server
import json
import threading
from playwright.sync_api import sync_playwright
INDEX_HTML = """<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><title>AngularJS Services Offline Lab</title></head>
<body>
<p id="loc-abs"></p>
<p id="loc-path"></p>
<p id="win-pathname"></p>
<p id="loc-watch-log"></p>
<p id="http-welcome"></p>
<p id="timeout-header"></p>
<p id="interval-ticks"></p>
<p id="custom-hex"></p>
<ul id="filter-hex-list"></ul>
<script>
(function () {
const watchers = [];
const $location = {
absUrl() {
return window.location.href;
},
path(newPath) {
if (newPath === undefined) {
const h = window.location.hash || "";
const stripped = h.replace(/^#!?/, "");
return stripped.split("?")[0] || "/";
}
const prev = this.path();
window.location.hash = "!" + newPath;
for (const fn of watchers) fn(newPath, prev);
return this;
},
$watchPath(fn) {
watchers.push(fn);
}
};
const $http = {
get(url) {
return fetch(url).then(async (res) => ({
data: await res.text(),
status: res.status
}));
}
};
function $timeout(fn, delay) {
return new Promise((resolve) => {
setTimeout(() => {
fn();
resolve();
}, delay);
});
}
function $interval(fn, delay, count) {
let ticks = 0;
const id = setInterval(() => {
ticks += 1;
fn(ticks);
if (ticks >= count) clearInterval(id);
}, delay);
return id;
}
// Service registry (constructor invoked with new, like app.service)
const services = {};
function registerService(name, Ctor) {
services[name] = new Ctor();
}
registerService("hexafy", function () {
this.myFunc = function (x) {
return Number(x).toString(16);
};
});
// Filter with injected custom service
const myFormatFilter = (function (hexafy) {
return function (x) {
return hexafy.myFunc(x);
};
})(services.hexafy);
// 1. $location vs window.location
const watchEvents = [];
$location.$watchPath((next, prev) => watchEvents.push(prev + "->" + next));
document.getElementById("loc-abs").textContent = $location.absUrl();
document.getElementById("loc-path").textContent = $location.path();
document.getElementById("win-pathname").textContent = window.location.pathname;
window.__changePath = function (p) {
$location.path(p);
document.getElementById("loc-watch-log").textContent = watchEvents.join(",");
return $location.path();
};
// 2. $http.get('/welcome.htm')
$http.get("/welcome.htm").then((response) => {
document.getElementById("http-welcome").textContent = response.data;
window.__httpDone = true;
});
// 3. $timeout
const headerEl = document.getElementById("timeout-header");
headerEl.textContent = "Hello World!";
window.__initialHeader = headerEl.textContent;
window.__timeoutDone = false;
$timeout(() => {
headerEl.textContent = "How are you today?";
window.__timeoutDone = true;
}, 120);
// 4. $interval (3 ticks @ 40ms)
const ticksEl = document.getElementById("interval-ticks");
ticksEl.textContent = "0";
window.__intervalDone = false;
$interval((n) => {
ticksEl.textContent = String(n);
if (n === 3) window.__intervalDone = true;
}, 40, 3);
// 5. Custom service hexafy + filter injection
document.getElementById("custom-hex").textContent = services.hexafy.myFunc(255);
const ul = document.getElementById("filter-hex-list");
for (const x of [255, 251, 200]) {
const li = document.createElement("li");
li.textContent = myFormatFilter(x);
ul.appendChild(li);
}
})();
</script>
</body>
</html>
"""
class LocalHandler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
if self.path.startswith("/app/index.html"):
body = INDEX_HTML.encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
elif self.path == "/welcome.htm":
body = b"Hello AngularJS Services"
self.send_response(200)
self.send_header("Content-Type", "text/plain; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
else:
self.send_response(404)
self.end_headers()
def log_message(self, format, *args):
pass
def launch_browser(p):
try:
return p.chromium.launch(headless=True)
except Exception:
return p.chromium.launch(headless=True, channel="chrome")
def main():
server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), LocalHandler)
port = server.server_address[1]
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
cases = []
try:
with sync_playwright() as p:
browser = launch_browser(p)
page = browser.new_page()
target_url = f"http://127.0.0.1:{port}/app/index.html#!/items/42?tab=info"
page.goto(target_url, wait_until="domcontentloaded")
init_header = page.locator("#timeout-header").text_content()
# Case 1: $location vs window.location
loc_abs = page.locator("#loc-abs").text_content()
loc_path_before = page.locator("#loc-path").text_content()
win_pathname = page.locator("#win-pathname").text_content()
loc_path_after = page.evaluate("() => window.__changePath('/orders')")
watch_log = page.locator("#loc-watch-log").text_content()
actual_1 = {
"abs_url_matches": loc_abs == target_url,
"location_path_before": loc_path_before,
"window_pathname": win_pathname,
"location_path_after": loc_path_after,
"watch_log": watch_log,
}
expected_1 = {
"abs_url_matches": True,
"location_path_before": "/items/42",
"window_pathname": "/app/index.html",
"location_path_after": "/orders",
"watch_log": "/items/42->/orders",
}
cases.append({
"name": "location_service_vs_window_location",
"expected": expected_1,
"actual": actual_1,
"passed": actual_1 == expected_1,
})
# Wait for async services ($http, $timeout, $interval)
page.wait_for_function("() => window.__httpDone && window.__timeoutDone && window.__intervalDone", timeout=5000)
# Case 2: $http.get welcome
actual_2 = {"welcome": page.locator("#http-welcome").text_content()}
expected_2 = {"welcome": "Hello AngularJS Services"}
cases.append({
"name": "http_service_get_welcome",
"expected": expected_2,
"actual": actual_2,
"passed": actual_2 == expected_2,
})
# Case 3: $timeout delayed update
actual_3 = {
"initial_header": page.evaluate("() => window.__initialHeader"),
"updated_header": page.locator("#timeout-header").text_content(),
}
expected_3 = {
"initial_header": "Hello World!",
"updated_header": "How are you today?",
}
cases.append({
"name": "timeout_service_delayed_update",
"expected": expected_3,
"actual": actual_3,
"passed": actual_3 == expected_3,
})
# Case 4: $interval periodic ticks
actual_4 = {"final_ticks": int(page.locator("#interval-ticks").text_content())}
expected_4 = {"final_ticks": 3}
cases.append({
"name": "interval_service_periodic_ticks",
"expected": expected_4,
"actual": actual_4,
"passed": actual_4 == expected_4,
})
# Case 5: Custom service hexafy + filter injection
actual_5 = {
"controller_hex_255": page.locator("#custom-hex").text_content(),
"filter_hex_list": page.locator("#filter-hex-list li").all_text_contents(),
}
expected_5 = {
"controller_hex_255": "ff",
"filter_hex_list": ["ff", "fb", "c8"],
}
cases.append({
"name": "custom_hexafy_service_and_filter_di",
"expected": expected_5,
"actual": actual_5,
"passed": actual_5 == expected_5,
})
browser.close()
finally:
server.shutdown()
server.server_close()
print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
- 核对 $location.path() 区分宿主路径并触发 watch;$http.get 返回 'Hello AngularJS Services';$timeout 刷新标题;$interval 准确执行 3 次;hexafy 转换 255->'ff' 且过滤器渲染 ['ff','fb','c8']。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:f003fe00d5d36e202058f7c60497da3a6126e31c69e5ceb91f006a84d1784a6d
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:9f99aee27a3ec9f89ef54238db59669d2f83f40c757488a01e3c0b86116a226d
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
为什么在 AngularJS 控制器里修改 $scope 数据时应优先用 $timeout 而非原生 window.setTimeout?自定义服务采用数组标注 ['hexafy', function(hexafy){...}] 有何工程作用?
展开参考解答
原生 setTimeout 回调在 AngularJS 监控上下文之外执行,修改 $scope 不会自动刷新视图(需额外调用 $scope.$apply()),而 $timeout 会自动触发脏检查并转发异常;数组依赖标注可防止代码压缩工具重命名函数形参后导致依赖注入器找不到对应服务名。