首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用jQuery/javascript命令的Angular 6数据订阅问题

使用jQuery/javascript命令的Angular 6数据订阅问题
EN

Stack Overflow用户
提问于 2018-10-16 04:34:54
回答 2查看 92关注 0票数 1

我有一个获取数据的HTTP服务。在我的组件中,我订阅了这个。

代码语言:javascript
复制
ngOnInit() {
    this.product = this.route.snapshot.data['product'];
    this.sectionService.getAll(this.product.id).subscribe( sections => {
      this.sections = sections;
    });
  }

我在组件HTML中有一个ngFor循环,它将为每个项目创建div。

代码语言:javascript
复制
<div class="col-md-9">      
   <div *ngFor="let section of sections" id="editor{{ section.id }}" contenteditable="true">
      {{ section.content }}
    </div>
    <!-- WYSIWYG -->
</div>

现在,我必须在每个div上运行一个javascript命令,以便启用编辑器。

代码语言:javascript
复制
this.sections.forEach(element => {
    const editor = CKEDITOR.inline('editor' + element.id);
});

如果我试图在subscribe函数或ngAfterViewInit()函数中添加javascript行,它就不能工作。

如果我尝试在ngOnInit()上创建一个静态数组,然后将我的javascript代码添加到ngAfterViewInit()中,它就能正常工作。

代码语言:javascript
复制
 ngOnInit() {
     this.product = this.route.snapshot.data['product'];
     this.sections = [ new Section(1, 'Hello', '<h1>test</h1>')];
 }

 ngAfterViewInit() {
    const editor = CKEDITOR.inline('editor1');
 }

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-10-16 07:14:03

如果你在订阅中运行它,页面可能还没有初始化。如果您在ngAfterViewInit中运行它,HTTP请求可能还没有完成。要确保两者都已准备就绪,请执行以下操作:

代码语言:javascript
复制
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
}
票数 1
EN

Stack Overflow用户

发布于 2018-10-16 05:12:08

如果你要在你的订阅中添加你的javascript,你必须去掉胖箭头符号,回到订阅中的普通函数声明,看看它是否工作。

代码语言:javascript
复制
this.sectionService.getAll(this.product.id).subscribe(function(sections){
  this.sections = sections;
  this.sections.forEach(element => {
    const editor = CKEDITOR.inline('editor' + element.id);
  });
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52824401

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档