我有一个获取数据的HTTP服务。在我的组件中,我订阅了这个。
ngOnInit() {
this.product = this.route.snapshot.data['product'];
this.sectionService.getAll(this.product.id).subscribe( sections => {
this.sections = sections;
});
}
我在组件HTML中有一个ngFor循环,它将为每个项目创建div。
<div class="col-md-9">
<div *ngFor="let section of sections" id="editor{{ section.id }}" contenteditable="true">
{{ section.content }}
</div>
<!-- WYSIWYG -->
</div>
现在,我必须在每个div上运行一个javascript命令,以便启用编辑器。
this.sections.forEach(element => {
const editor = CKEDITOR.inline('editor' + element.id);
});
如果我试图在subscribe函数或ngAfterViewInit()函数中添加javascript行,它就不能工作。
如果我尝试在ngOnInit()上创建一个静态数组,然后将我的javascript代码添加到ngAfterViewInit()中,它就能正常工作。
ngOnInit() {
this.product = this.route.snapshot.data['product'];
this.sections = [ new Section(1, 'Hello', '<h1>test</h1>')];
}
ngAfterViewInit() {
const editor = CKEDITOR.inline('editor1');
}
如何才能使此功能适用于订阅?
发布于 2018-10-16 07:14:03
如果你在订阅中运行它,页面可能还没有初始化。如果您在ngAfterViewInit中运行它,HTTP请求可能还没有完成。要确保两者都已准备就绪,请执行以下操作:
sections = []
ngOnInit() {
this.product = this.route.snapshot.data['product'];
this.sectionService.getAll(this.product.id).subscribe( sections => {
this.sections = sections;
});
}
ngAfterViewInit() {
const interval = setInterval(() => {
if (this.sections.length) {
this.sections.forEach(element => {
const editor = CKEDITOR.inline('editor' + element.id);
});
clearInterval(interval); // stop further executions of this code
}
}, 100) // check if sections are ready every 100ms
}
发布于 2018-10-16 05:12:08
如果你要在你的订阅中添加你的javascript,你必须去掉胖箭头符号,回到订阅中的普通函数声明,看看它是否工作。
this.sectionService.getAll(this.product.id).subscribe(function(sections){
this.sections = sections;
this.sections.forEach(element => {
const editor = CKEDITOR.inline('editor' + element.id);
});
});
https://stackoverflow.com/questions/52824401
复制相似问题