FakeAsync/tick(Async/whenStable)与detectChanges() [英] FakeAsync/tick (Async/whenStable) vs detectChanges()

查看:139
本文介绍了FakeAsync/tick(Async/whenStable)与detectChanges()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您能帮我区分这两件事吗?

Could you please help me differentiate those two things.

根据我的理解,如果仅使用可观察的方法,则可以使用detectChanges().因此,您可以直接更改组件属性或监视服务调用并返回一个可观察的对象,然后调用detectChanges(),更改将在html元素上可用.

According to my understanding, if you only work with observable, you can use detectChanges(). So you can change a component property directly or spy on a service call and return an observable, then you call detectChanges(), the changes will be available on html elements.

但是对于输入字段上的[[ngModel)],您需要调用tick()才能将更改呈现在html元素上.

But for [(ngModel)] on input fields you need to call tick() for the changes to be render on html element.

因此,如果我知道他们的工作以及何时使用的话,那将是很棒的事情.

So I'd it would be great if I know what they do and when to use what.

谢谢.

推荐答案

detectChanges

方法detectChanges ViewRef 上可用.

class ViewRef extends ChangeDetectorRef {
  // inherited from core/ChangeDetectorRef
  markForCheck(): void   <-----------------------------
  detach(): void
  detectChanges(): void
  checkNoChanges(): void
  reattach(): void
}

ViewRef是组件的基础表示.在编写测试而不是ViewRef时,引入了另一个抽象,它是fixture:

ViewRef is an underlying representation of a component. When writing tests instead of ViewRef another abstraction is introduced which is fixture:

fixture = TestBed.createComponent(BannerComponent);

它包装类似于ViewRef的组件.

detectChanges方法对基础组件运行更改检测,并执行以下操作:

detectChanges method runs change detection for the underlying component and performs the following operations:

  • 更新输入绑定属性
  • 更新DOM

和许多其他.

要了解更多信息,您可以阅读

To learn more you can read Everything you need to know about change detection in Angular. So in order to validate changes in the DOM or validate input bindings you need to run detectChanges.

角度文档很好地描述了它:

tick函数是Angular测试实用程序之一, fakeAsync的伴侣.您只能在fakeAsync正文中调用它.

The tick function is one of the Angular testing utilities and a companion to fakeAsync. You can only call it within a fakeAsync body.

调用tick()模拟时间的流逝,直到所有未决 异步活动完成,包括 此测试用例中的getQuote承诺.

Calling tick() simulates the passage of time until all pending asynchronous activities finish, including the resolution of the getQuote promise in this test case.

对于ngModel,您需要调用它,因为在ngModel内部创建的控件是异步注册的.以下是 Victor Savkin在表单上的文章的引文:

With ngModel you need to call it because the control that is created inside ngModel is registered asynchonously. Here is the quote from the article by Victor Savkin on forms:

为使其正常工作,NgModel不会同步添加表单控件 在微任务中完成.在上面的示例中,三个ngModel将 安排三个微任务以添加发言人,标题和highRating 控件.

To make it work, NgModel doesn’t add a form control synchronously — it does it in a microtask. In the example above, the three ngModels will schedule three microtasks to add the speaker, title, and highRating controls.

这篇关于FakeAsync/tick(Async/whenStable)与detectChanges()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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