我在 Angular 10 中有一个非常简单的组件。提交表单时,会创建并存储 canvas
元素的 Blob
。
因此,onSubmit()
函数的相关部分如下所示:
onSubmit(): void {
const canvas: HTMLCanvasElement = getCanvas();
canvas.toBlob((blob: Blob) => {
this.service.create(blob).pipe(first()).subscribe((response: boolean) => {
this.isSuccessful = response;
});
}, 'image/png', 1);
}
问题是,isSuccessful
已更改,但这些更改并未反射(reflect)在
模板。
所以我所做的是使用 ChangeDetectorRef
手动触发更改检测:
onSubmit(): void {
const canvas: HTMLCanvasElement = getCanvas();
canvas.toBlob((blob: Blob) => {
this.service.create(blob).pipe(first()).subscribe((response: boolean) => {
this.isSuccessful = response;
this.cdr.detectChanges();
});
}, 'image/png', 1);
}
现在,这可行了。 但是为什么这里需要它?在所有其他情况下,当我使用像这样的箭头函数时,不需要更改检测器。 toBlob()
方法似乎有所不同。
PS:当 service.create()
方法位于 toBlob()
方法之外时,也不需要 cdr
。
最佳答案
未触发更改检测,因为 canvas.toBlob
在 Angular Zone 之外执行回调。 。调用 ChangeDetectorRef.detectChanges
的另一种方法是确保代码在 Angular 区域内执行 NgZone.run :
import { NgZone } from '@angular/core';
...
constructor(private ngZone: NgZone) { }
canvas.toBlob((blob: Blob) => {
this.ngZone.run(() => {
// Run the code here
});
}, 'image/png', 1);
参见this stackblitz进行演示。
关于javascript - 为什么在使用带有箭头函数的 canvas.toBlob() 时,Angular 的 ChangeDetection 没有被触发?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63712127/