要在长时间运行的任务中保持 Angular 8 的 toast/snackbar 活跃,可以使用 Angular 的 ChangeDetectorRef
和 ApplicationRef
。
首先,确保你已经导入了 ChangeDetectorRef
和 ApplicationRef
。
import { ChangeDetectorRef, ApplicationRef } from '@angular/core';
然后,在组件的构造函数中注入 ChangeDetectorRef
和 ApplicationRef
。
constructor(private cdr: ChangeDetectorRef, private appRef: ApplicationRef) { }
接下来,在长时间运行的任务中,你可以使用 ChangeDetectorRef
的 detectChanges()
方法来手动触发变更检测。
longRunningTask() {
// 长时间运行的任务
this.cdr.detectChanges();
}
这样可以确保在任务运行期间更新的数据能够被正确地显示在视图中。
另外,你也可以使用 ApplicationRef
的 tick()
方法来手动触发变更检测。
longRunningTask() {
// 长时间运行的任务
this.appRef.tick();
}
这与 ChangeDetectorRef
的 detectChanges()
方法类似,都可以用来保持视图的活跃状态。
完整示例代码如下:
import { Component, ChangeDetectorRef, ApplicationRef } from '@angular/core';
@Component({
selector: 'app-example',
template: `
Toast / Snackbar
`
})
export class ExampleComponent {
showToast = false;
constructor(private cdr: ChangeDetectorRef, private appRef: ApplicationRef) { }
startLongRunningTask() {
this.showToast = true;
// 长时间运行的任务
this.cdr.detectChanges(); // 或者 this.appRef.tick();
}
}
这样,当你点击 "开始任务" 按钮时,toast/snackbar 将会在长时间运行的任务期间保持活跃状态。