angular - 没有视图的动态组件上的输出
问题描述
在 Angular 8 项目中,我使用以下代码创建了一些没有 viewref 的动态组件:
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(HelloComponent);
const componentRef = componentFactory.create(this.injector);
componentRef.changeDetectorRef.detectChanges();
componentRef.instance.slideContentRendered.pipe(first()).subscribe(x => {console.log('does not work', x);});
在 HelloComponent 本身中,我正在等待一些异步任务完成,然后发出 slideContentRendered 但我没有进入订阅方法主体。
在这里你可以看到一个示例应用程序 https://stackblitz.com/edit/angular-krx3y6
我怎样才能访问输出?如果我尝试使用以下代码对 viewref 进行相同操作:
const componentRef = viewContainerRef.createComponent(componentFactory);
componentRef.instance.slideContentRendered.pipe(first()).subscribe(x => {console.log('it works', x);});
解决方案
使用 BehaviorSubject,只要某处有侦听器,它就会发出值。订阅 EventEmitter 仅在发射时存在直接侦听器时触发。因此,请进行以下更改:
slideContentRendered = new BehaviorSubject<string>('hey');
ngAfterViewInit() {
console.log('AfterViewInitTriggered');
this.slideContentRendered.next('teeest!')
}
trigger() {
this.testService.renderHtmlFromPresentation().subscribe(x => console.log(x));
}
推荐阅读
- python - Pandas - 如何根据其他列减去行值?
- python - 如何在python中计算随机森林的训练和测试数据之间的准确性
- java - 更改 ListView 一行的文本颜色
- go - 无法将 nil(无类型的 nil 值)转换为 struct
- selenium - 错误:“列表”对象没有“点击”属性 - Selenium Webdriver
- javascript - 如何改进这个 JS 代码看起来更优雅
- html - align-items:stretch 和 align-self:stretch 在没有固定高度的 flex 行中不起作用
- etl - Pentaho Data Integration 8.2 - Excel Writer 上的时间戳空白
- python-requests - 如何使用 Requests 库和 Python 3.8.5 禁用“check_hostname”?
- node.js - 使用 nodejs 将图像更新到 AWS S3