首页 > 解决方案 > 等待 AngularJS 服务完成运行(chrome 控制台)

问题描述

我正在通过 Chrome 控制台操作一些角度服务/功能。 (我必须专门为我正在处理的任务执行此操作)。

我想要做的是等待AddBagIfLimitNotReached()函数执行并完成运行。然后才访问变量this.option.Quantity

angular.element(document.querySelector(".quantity-button")).controller()._registeredControls[1].Scope.AddBagIfLimitNotReached = async function(n) {
    console.log("tthis", this)
        if (this.HasReachedMaximumBaggageAllowance()) {
            angular.element(document.querySelector(".quantity-button")).controller()._registeredControls[1].LuggageDrawersService.OpenLuggageLimitReachedDrawer();
            return;
        }
        this.AddBag(n);
        console.log("Quantity", this.option.Quantity);
};

使用此功能,我将产品添加到我的购物篮中。并且this.option.Quantity应该 console.log 1。但它实际上是 consoles.log 0

但是,如果我检查对象本身,它会显示1.

所以我认为正在发生的事情是,在袋子实际完成添加到篮子之前,我正在控制台记录我的袋子数量。

比如我加了一个settimeout2秒的,正确的bag值=1就是console.logged。

angular.element(document.querySelector(".quantity-button")).controller()._registeredControls[1].Scope.AddBagIfLimitNotReached = async function(n) {
    console.log("tthis", this)
        if (this.HasReachedMaximumBaggageAllowance()) {
            angular.element(document.querySelector(".quantity-button")).controller()._registeredControls[1].LuggageDrawersService.OpenLuggageLimitReachedDrawer();
            return;
        }
        this.AddBag(n);

        // Returns 1
        setTimeout(function(){ console.log("Quantity", this.option.Quantity); }, 2000);
};

有没有更好的方法可以在不使用 settimeout 的情况下实现这一目标?我已经尝试过 async/await/promises,但我似乎仍然找不到等待函数完成加载的方法。

Async/await 返回一个错误——它不喜欢这个函数this.HasReachedMaximumBaggageAllowance()并抛出一个错误声明this.HasReachedMaximumBaggageAllowance is not a function

任何提示/想法将不胜感激。

标签: angularjsasynchronousasync-awaitpromise

解决方案


我找到了一个解决方案,我正在使用$watch,来观察this对象中的键/值。这似乎有效:

angular.element(document.querySelector(".quantity-button.plus-button")).controller()._registeredControls[1].Scope.AddBagIfLimitNotReached = function(n) {
    let bagCount = this.option.Quantity;
    console.log("bagCount", bagCount);

        if (this.HasReachedMaximumBaggageAllowance()) {
            angular.element(document.querySelector(".quantity-button.plus-button")).controller()._registeredControls[1].LuggageDrawersService.OpenLuggageLimitReachedDrawer();
            return;
        };

        this.AddBag(n);
        this.$watch("this.option.Quantity", function (newValue) {
            console.log(`Value of foo changed ${newValue}`);
            if (newValue > 0) {
                document.querySelector(`.luggage-tile-weight-${n.Weight} .tile-title .tick-box`).classList.add("green-tick");
                displayGreenTickNoBagSelected();
            };
            if (newValue === 0) {
                document.querySelector(`.luggage-tile-weight-${n.Weight} .tile-title .tick-box`).classList.remove("green-tick");
                displayGreenTickNoBagSelected();
            };
        });
};

推荐阅读