You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Chrome控制台中等待AngularJS服务执行完成的非setTimeout方案咨询

问题根因说明

  1. this.HasReachedMaximumBaggageAllowance is not a function 报错是函数执行时this指向丢失,没有绑定到原Scope对象导致。
  2. 打印this.option.Quantity为0、但直接查看对象为1,是因为AddBag内部包含异步逻辑(如接口请求、Angular变更检测异步队列),同步读取时变量更新还未完成。

最优实现方案

所有方案都提前保存上下文避免this指向丢失,不需要硬编码固定延迟时间,和框架执行周期对齐。

方案1:await 异步方法(适配AddBag返回Promise的场景)

angular.element(document.querySelector(".quantity-button")).controller()._registeredControls[1].Scope.AddBagIfLimitNotReached = async function(n) {
    const self = this; // 提前保存Scope上下文,解决this指向丢失问题
    console.log("tthis", self)
    if (self.HasReachedMaximumBaggageAllowance()) {
        angular.element(document.querySelector(".quantity-button")).controller()._registeredControls[1].LuggageDrawersService.OpenLuggageLimitReachedDrawer();
        return;
    }
    // 等待AddBag异步逻辑完全执行完成
    await self.AddBag(n);
    console.log("Quantity", self.option.Quantity);
};

方案2:使用$evalAsync对齐变更检测周期(适配AngularJS 1.x所有场景)

如果AddBag不返回Promise,用框架内置的$evalAsync方法,会在当前轮变更检测、DOM更新完成后触发回调:

angular.element(document.querySelector(".quantity-button")).controller()._registeredControls[1].Scope.AddBagIfLimitNotReached = function(n) {
    const self = this;
    console.log("tthis", self)
    if (self.HasReachedMaximumBaggageAllowance()) {
        angular.element(document.querySelector(".quantity-button")).controller()._registeredControls[1].LuggageDrawersService.OpenLuggageLimitReachedDrawer();
        return;
    }
    self.AddBag(n);
    // 回调会在变量更新完成后自动触发,无需固定延迟
    self.$evalAsync(function() {
        console.log("Quantity", self.option.Quantity);
    })
};

方案3:监听变量变化触发回调(最稳妥的通用方案)

直接监听目标变量的变更,触发一次后自动销毁监听,避免内存泄漏:

angular.element(document.querySelector(".quantity-button")).controller()._registeredControls[1].Scope.AddBagIfLimitNotReached = function(n) {
    const self = this;
    console.log("tthis", self)
    if (self.HasReachedMaximumBaggageAllowance()) {
        angular.element(document.querySelector(".quantity-button")).controller()._registeredControls[1].LuggageDrawersService.OpenLuggageLimitReachedDrawer();
        return;
    }
    self.AddBag(n);
    // 注册变量监听,触发后立刻销毁
    const unWatch = self.$watch('option.Quantity', function(newVal) {
        // 可自行补充判断条件,比如newVal === 1
        if (newVal) {
            console.log("Quantity", newVal);
            unWatch();
        }
    })
};

内容的提问来源于stack exchange,提问作者Reena Verma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 15:45:07