我使用的是角度6。当我尝试将ZoneAwarePromise
转换为Observable
时,一个http调用返回一个Promise
。同样,then块也不会被调用。
const login = this.authService.login(email, password).toPromise()
login.then(() => {\* not getting called*\})
有人可以解释什么是ZoneAwarePromise
吗?
答案 0 :(得分:4)
Angular严重依赖zone.js来保持跨异步任务的执行上下文。它包装在名为NgZone
的可注入服务中。
这些区域包装了用于运行异步任务的常见JS对象,其中包括Promises。在Zone
中将其作为Task,MicroTask等进行维护。
ZoneAwarePromise
在功能上仍然与普通Promise相同,但是内部仍在注意Zone
的执行上下文,而Zone
可以知道该Promise何时完成。>
在Angular中,这种执行上下文几乎总是意味着运行更改检测。
答案 1 :(得分:1)
Promise是一个构造函数,该构造函数在运行时在浏览器中从ZoneAwarePromise()
解析为zone.js
。请访问以下link以获取更多见解。
答案 2 :(得分:1)
We use Angular because we can only change model and it will update view automatically for us, based on declarative templates that we provide via metadata.
The way Angular handles this is by intercepting three types of events:
setTimeout
, setInterval
) andfetch
, XHR, HttpClient
).Interally, this is done via zones. When you load setTimeout
, it actually swaps the default setTimeout
implementation with its own implementation, but with the same signature. When you call setTimeout
, you're not even aware that you're using zones.
On a very high-level, it pretty much works like this:
const originalSetTimeout = window.setTimeout
window.setTimeout = (fn, time) => {
setTimeout(() => { fn(); updateView() }, time)
}
It pretty much just executes your function as usual and then calls another thing -- which is used by Angular do update the view.
ZoneAwarePromise
is just a way to use Promise
so that zone is aware of it. You can find implementation details in source code of Zone.js, but that's the gist of it.