问题描述: 在Angular中,当在Promise内部尝试发射事件时,事件似乎无法被触发。
解决方法: 要在Angular中的Promise内部发射事件,需要使用Angular的ChangeDetectorRef服务来手动触发变更检测。
以下是解决方法的代码示例:
import { Component, OnInit, ChangeDetectorRef } from '@angular/core';
@Component({
selector: 'app-my-component',
template: `
{{ result }}
`
})
export class MyComponent implements OnInit {
result: string;
constructor(private cdRef: ChangeDetectorRef) {}
ngOnInit() {}
startAsyncTask() {
this.result = 'Task started';
// 模拟异步任务
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
this.result = 'Task completed';
// 手动触发变更检测
this.cdRef.detectChanges();
resolve();
}, 2000);
});
// 可选:可以在任务完成后执行一些额外的逻辑
promise.then(() => {
console.log('Task finished');
});
}
}
在上面的代码中,我们使用了ChangeDetectorRef服务来手动触发变更检测。在Promise的resolve回调中,我们调用了this.cdRef.detectChanges()
来通知Angular检查组件的变更。这将触发组件的重新渲染,并更新模板中的绑定。
请注意,ChangeDetectorRef服务必须在组件的构造函数中注入,并且不能在构造函数外部使用。这是因为ChangeDetectorRef是Angular内部的服务,它只能在组件的上下文中使用。