Angular 6 数据订阅问题与 jQuery/javascript 命令



我有一个获取数据的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);
});

如果我尝试在订阅函数或 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');
}

如何使此功能适用于订阅?

如果在订阅中运行它,则页面可能尚未初始化。如果在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
}

如果你在订阅中添加你的javascript,你必须去掉胖箭头符号,回到订阅中的正常函数声明,看看它是否有效。

this.sectionService.getAll(this.product.id).subscribe(function(sections){
this.sections = sections;
this.sections.forEach(element => {
const editor = CKEDITOR.inline('editor' + element.id);
});
});

最新更新