在angular2中,使用zone.run与changeDetecotor.markForCheck()的优势 [英] In angular2, advantage of using zone.run vs changeDetecotor.markForCheck()

查看:191
本文介绍了在angular2中,使用zone.run与changeDetecotor.markForCheck()的优势的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道使用一个相对于另一个有什么优点或缺点:

I am wondering what's the advantage or disadvantage of using one over other:

 constructor(private app:ApplicationRef, private ref:ChangeDetectorRef) {
    this.ref.markForCheck();
    // OR
    this.ref.detectChanges()  
    // will do same thing?
 ...

vs

zone.run

(() => doSomething())
    ...

vs

  app.tick();

从本质上讲,它们全部将标记该组件以进行检查和更新/重绘UI.

they all essentially will mark the component for checking and updates / redraw the UI.

我知道app.tick()会在整个应用程序中使用它,但是在我的测试中,它实际上并没有强制UI进行更新.

I know app.tick() will do it for the entire app, but in my tests it didn't actually force the UI to update.

zone.runmarkforCheck都强制UI在下一个区域周期检查时更新,那么为什么要在另一个区域上使用它呢?

zone.run and markforCheck both force the UI to update on the next zone cycle check, so why use one over the other?

推荐答案

如果运行只影响当前组件的代码,例如

If you run code that only affects the current component, like

someServiceThatRunsOutsideZone.getData()
.subscribe(data => {
  this.data = data;
  this.ref.markForCheck();
});

this.ref.markForCheck()很好.

例如,如果您在Angulars区域之外进行this.router.navigateXxx(...)操作,那么很难知道this.ref.markForCheck()是否将覆盖所有可能通过此相当复杂的操作更改其状态的元素.

If you do for example this.router.navigateXxx(...) outside Angulars zone then it's hard to know if this.ref.markForCheck() will cover all elements that might get their state changed by this rather complex operation.

此外,如果this.router.navigateXxx(...)调用一些异步调用,您的markForCheck将在这些异步调用完成之前运行,并且在最后可能不会调用更改检测.

Also if this.router.navigateXxx(...) invokes some async calls, your markForCheck will be run before these async calls are completed and will not invoke change detection at the end as it is probably necessary.

使用

this.zone.run(() => this.router.navigateXxx(...))

没关系,因为this.router.navigateXxx()以及该调用调用的所有代码(同步和异步)将在Angulars区域内运行并使用其修补的API.

it doesn't matter because this.router.navigateXxx() and all code that is invoked by that call (sync and async) will run inside Angulars zone and use its patched API.

我不知道app.tickmarkForCheck之间的确切区别,但是app.tick确实也有上面针对markForCheck

I don't know about the exact difference between app.tick and markForCheck but app.tick also does have the disadvantage explained above for markForCheck

这篇关于在angular2中,使用zone.run与changeDetecotor.markForCheck()的优势的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆