蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

验证 $location 路径监听、$http/$timeout/$interval 及自定义 hexafy 服务注入过滤器

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-services.py
explore-services.py283 行
"""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()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

入口文件:projects/angularjs-services-lab/explore-services.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-services.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:AngularJS

课程关联工程包(登记关联26章) · 含当前章节或实例 · mbskycom202612a851.zip

下载课程关联工程包:AngularJS

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a870.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习