角度变化检测承诺-混合应用

时间:2019-01-10 23:17:01

标签: javascript angularjs angular

我们正在将AngularJS项目升级到Angular7。我们正在遵循建议的“混合”方法,这两个框架可以并排运行。我们正遇到一些带有原生承诺的变更检测问题。本质上,AngularJS(服务A)服务使用的是“降级”的Angular 7服务(服务B)。在迁移之前,所有ServiceB的方法都返回$ q的defer.promise。但是,既然服务B是Angular 7服务,我们将返回常规的Promises,但是在Change Detection中不能很好地发挥作用。

我尝试将SerivceB的呼叫包装在$ q的承诺中,我现在看到它工作正常。但是,这不是可行的解决方案,因为ServiceA将在将来升级为Angular 7服务。

当前代码

---
title: "working example"
date: 2019-01-08T18:16:47-08:00
draft: false
---

现在,当我将ServiceB getOrders调用包装在$ qs中时,它会变得很有趣,因为这样UI就会更新

ServiceA.get = function(order) {
    //do some work
    //ServiceB is the downgraded Angular 7 service
    //now returns a native promise

   return ServiceB.getOrders(order) 
}

ServiceA.processBatch = function(order,observer) {
    ServiceA.get(order)
    .then(function(resolve) {
        //should trigger the UI update in the Controller (still Angular JS)
        observer.onComplete(resolve)
    })
    .catch(function(err) {
        observer.onError(err)
    })
}

我希望不会有什么区别,但是当检查调用栈时,我看到常规的promise解析在区域内运行,但是当使用$ q时,我看到遵循了$ digest。

我不明白为什么会这样。这是代码的简化示例。实际上,还有很多事情要做,这就是为什么我无法从ServiceA.get = function(order) { //do some work //ServiceB is the downgraded Angular 7 service //now returns a native promise var defer = $q.defer() ServiceB.getOrders(order) .then(function(resolve) { defer.resolve(resolve)}) .catch(function(err) { defer.reject(err);}); return defer.promise; }

退回承诺

1 个答案:

答案 0 :(得分:1)

I found the issue after a few bad days at the office. The issue was that ServiceA was using a third party library. ServiceA was depending on some callbacks by that third party library, whenever those callback ran, I was not in the "angular" zone anymore. I was in the "" zone. My question was poorly stated and my dumbed down code did not include the part about the third party library. Moral of the story is to inspect the Call Stack to see if I am in the Angular zone or "root" zone. If you are in the root zone it is likely due to a third party library that uses events that are not monkey patched by Angular