"""Offline Playwright Chromium lab for AngularJS Ch 24: routing (ngRoute, $routeProvider, ng-view, ng-template)."""
import json
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from playwright.sync_api import sync_playwright
ROUTE_HTML = """<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><title>AngularJS 路由离线实验</title></head>
<body>
<script type="text/ng-template" id="embedded.home.html"><h1>Home</h1><p class="ctrl-info"></p></script>
<script type="text/ng-template" id="embedded.about.html"><h1>About</h1><p class="ctrl-info"></p></script>
<nav id="nav-basic">
<a id="lnk-home" href="#!/">首页</a>
<a id="lnk-computers" href="#!/computers">电脑</a>
<a id="lnk-printers" href="#!/printers">打印机</a>
<a id="lnk-unknown" href="#!/blabla">其他</a>
<a id="lnk-tpl-home" href="#!/tpl-home">内嵌Home</a>
<a id="lnk-tpl-about" href="#!/tpl-about">内嵌About</a>
<a id="lnk-remote" href="#!/remote-computers">远程模板</a>
</nav>
<div id="view" ng-view></div>
<script>
// Self-contained offline ngRoute ($routeProvider + ng-view + $templateCache) equivalence runtime
function createRouteEngine(hashPrefix) {
const routes = [];
let fallback = null;
const controllers = {};
const templateCache = new Map();
document.querySelectorAll('script[type="text/ng-template"]').forEach((s) => {
templateCache.set(s.id, s.textContent.trim());
});
const $routeProvider = {
when(path, cfg) {
routes.push({ path, cfg });
return $routeProvider;
},
otherwise(cfg) {
fallback = cfg;
return $routeProvider;
}
};
const $route = { current: null };
function currentPath() {
const raw = window.location.hash || '';
const prefix = '#' + hashPrefix;
if (raw.startsWith(prefix)) return raw.slice(prefix.length) || '/';
if (raw.startsWith('#/')) return raw.slice(1);
return '/';
}
async function renderRoute() {
const path = currentPath();
const hit = routes.find((r) => r.path === path);
if (!hit) {
if (fallback && fallback.redirectTo) {
window.location.hash = '#' + hashPrefix + fallback.redirectTo;
return renderRoute();
}
return null;
}
const cfg = hit.cfg;
if (cfg.redirectTo) {
window.location.hash = '#' + hashPrefix + cfg.redirectTo;
return renderRoute();
}
const resolved = {};
if (cfg.resolve) {
for (const [k, fn] of Object.entries(cfg.resolve)) {
resolved[k] = await fn();
}
}
let html = '';
if (typeof cfg.template === 'string') {
html = cfg.template;
} else if (cfg.templateUrl) {
if (templateCache.has(cfg.templateUrl)) {
html = templateCache.get(cfg.templateUrl);
} else {
const resp = await fetch(cfg.templateUrl);
html = await resp.text();
}
}
$route.current = { originalPath: hit.path, controller: cfg.controller || null, controllerAs: cfg.controllerAs || null, resolved };
const view = document.querySelector('[ng-view]');
view.innerHTML = html;
if (cfg.controller && controllers[cfg.controller]) {
const scope = {};
const ctrlInst = {};
controllers[cfg.controller].call(ctrlInst, scope, $route, resolved);
if (cfg.controllerAs) scope[cfg.controllerAs] = ctrlInst;
const infoEl = view.querySelector('.ctrl-info');
if (infoEl) {
infoEl.textContent = (scope.label || ctrlInst.label || '') + (resolved.tag ? ':' + resolved.tag : '');
}
}
return $route.current;
}
return {
$routeProvider,
$route,
controller(name, fn) { controllers[name] = fn; },
renderRoute,
currentPath
};
}
const engine = createRouteEngine('!');
engine.controller('HomeController', function($scope, $route, resolved) {
$scope.label = 'HomeController';
this.label = 'homeVm';
$scope.$route = $route;
});
engine.controller('AboutController', function($scope, $route, resolved) {
$scope.label = 'AboutController';
this.label = 'aboutVm';
$scope.$route = $route;
});
engine.$routeProvider
.when('/', { template: '这是首页页面' })
.when('/computers', { template: '这是电脑分类页面' })
.when('/printers', { template: '这是打印机页面' })
.when('/tpl-home', {
templateUrl: 'embedded.home.html',
controller: 'HomeController',
controllerAs: 'vm',
resolve: { tag: () => Promise.resolve('ready-home') }
})
.when('/tpl-about', {
templateUrl: 'embedded.about.html',
controller: 'AboutController',
controllerAs: 'vm',
resolve: { tag: () => Promise.resolve('ready-about') }
})
.when('/remote-computers', {
templateUrl: '/views/computers.html'
})
.otherwise({ redirectTo: '/' });
window.__routeEngine = engine;
window.addEventListener('hashchange', () => { engine.renderRoute(); });
engine.renderRoute();
</script>
</body>
</html>
"""
class _RouteHandler(BaseHTTPRequestHandler):
hits = []
def log_message(self, format, *args):
return
def _send(self, body: str):
data = body.encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
def do_GET(self):
_RouteHandler.hits.append(self.path)
if self.path == "/":
self._send(ROUTE_HTML)
elif self.path == "/views/computers.html":
self._send('<section id="remote-tpl"><h3>外部模板:电脑分类</h3></section>')
else:
self.send_error(404)
def launch_browser(p):
try:
return p.chromium.launch(headless=True)
except Exception:
return p.chromium.launch(headless=True, channel="chrome")
def main():
_RouteHandler.hits = []
srv = ThreadingHTTPServer(("127.0.0.1", 0), _RouteHandler)
port = srv.server_address[1]
t = threading.Thread(target=srv.serve_forever, daemon=True)
t.start()
cases = []
try:
with sync_playwright() as p:
browser = launch_browser(p)
try:
page = browser.new_page()
page.goto(f"http://127.0.0.1:{port}/", wait_until="load")
# Case 1: Basic #!/ route switching & .otherwise redirect with zero extra '/' HTTP requests
page.click("#lnk-home")
v_home = page.locator("#view").inner_text()
page.click("#lnk-computers")
v_comp = page.locator("#view").inner_text()
page.click("#lnk-printers")
v_print = page.locator("#view").inner_text()
page.click("#lnk-unknown")
page.wait_for_function("() => window.location.hash === '#!/'")
v_fallback = page.locator("#view").inner_text()
hash_after_fallback = page.evaluate("() => window.location.hash")
root_requests = sum(1 for h in _RouteHandler.hits if h == "/")
res1 = {
"home": v_home,
"computers": v_comp,
"printers": v_print,
"fallback_view": v_fallback,
"fallback_hash": hash_after_fallback,
"server_root_hits": root_requests,
}
exp1 = {
"home": "这是首页页面",
"computers": "这是电脑分类页面",
"printers": "这是打印机页面",
"fallback_view": "这是首页页面",
"fallback_hash": "#!/",
"server_root_hits": 1,
}
cases.append(dict(
name="hashbang_route_switching_and_otherwise",
expected=exp1,
actual=res1,
passed=(res1 == exp1),
))
# Case 2: Pre-1.6 '#' vs 1.6+ '#!' prefix resolution & unchanged pathname
res2 = page.evaluate("""() => {
window.location.hash = '#/computers';
const pre16Path = window.__routeEngine.currentPath();
const pathname1 = window.location.pathname;
window.location.hash = '#!/printers';
const v16Path = window.__routeEngine.currentPath();
const pathname2 = window.location.pathname;
return {
pre16_parsed_path: pre16Path,
v16_parsed_path: v16Path,
pathname_unchanged: pathname1 === '/' && pathname2 === '/'
};
}""")
exp2 = {
"pre16_parsed_path": "/computers",
"v16_parsed_path": "/printers",
"pathname_unchanged": True,
}
cases.append(dict(
name="pre16_hash_prefix_vs_16_hashbang",
expected=exp2,
actual=res2,
passed=(res2 == exp2),
))
# Case 3: Embedded script[type="text/ng-template"] + controller + controllerAs + resolve
page.click("#lnk-tpl-home")
page.wait_for_selector("#view h1")
home_h1 = page.locator("#view h1").inner_text()
home_info = page.locator("#view .ctrl-info").inner_text()
page.click("#lnk-tpl-about")
page.wait_for_function("() => document.querySelector('#view h1')?.textContent === 'About'")
about_h1 = page.locator("#view h1").inner_text()
about_info = page.locator("#view .ctrl-info").inner_text()
res3 = {
"home_h1": home_h1,
"home_ctrl_resolve": home_info,
"about_h1": about_h1,
"about_ctrl_resolve": about_info,
}
exp3 = {
"home_h1": "Home",
"home_ctrl_resolve": "HomeController:ready-home",
"about_h1": "About",
"about_ctrl_resolve": "AboutController:ready-about",
}
cases.append(dict(
name="embedded_ng_template_and_controller",
expected=exp3,
actual=res3,
passed=(res3 == exp3),
))
# Case 4: Remote templateUrl fetched over HTTP into ng-view
page.click("#lnk-remote")
page.wait_for_selector("#remote-tpl h3")
remote_text = page.locator("#remote-tpl h3").inner_text()
remote_hits = sum(1 for h in _RouteHandler.hits if h == "/views/computers.html")
res4 = {
"remote_heading": remote_text,
"template_http_hits": remote_hits,
}
exp4 = {
"remote_heading": "外部模板:电脑分类",
"template_http_hits": 1,
}
cases.append(dict(
name="remote_template_url_fetch",
expected=exp4,
actual=res4,
passed=(res4 == exp4),
))
finally:
browser.close()
finally:
srv.shutdown()
srv.server_close()
print(json.dumps({"cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
入口文件:projects/angularjs-routing-lab/explore-routing.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-routing.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联26章) · 含当前章节或实例 · mbskycom202612a851.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a867.zip