2017-03-02 163 views
2

我想在初始化我的轮播之后在jQuery中执行“each”函数。但是,在ngOnInit()函数中,我有一个与http.get不同步的任务来获取我需要初始化传送带的数据。在异步任务后执行jquery

我的代码:

ngOnInit() { this.list(); $('.carousel').carousel(); }

list(): void { 
    this.http.get(`http://localhost:8082/api/list`) 
     .subscribe(response => { 
      this.c= response.json().data; 
     }, error => { 
      this.error = error; 
     }) 
} 

ngAfterViewInit() { 
    // Your jQuery code goes here 
    $('.carousel .item').each(function() { 
     var next = $(this).next(); 
     if (!next.length) { 
      next = $(this).siblings(':first'); 
     } 
     next.children(':first-child').clone().appendTo($(this)); 

     for (var i = 0; i < 2; i++) { 
      next = next.next(); 
      if (!next.length) { 
       next = $(this).siblings(':first'); 
      } 

      next.children(':first-child').clone().appendTo($(this)); 
     } 
    }); 
} 

的每个功能不执行...

+0

使用信号灯,你从异步调用响应后,修改某些全局变量,或一些DOM元素,并检查持续在每个函数之前,只有在异步调用修改后才能继续。 –

+0

初始化您的异步方法回调内的传送带。 – ADyson

回答

1

这是因为从你的异步功能的响应还没有。您可以在收到您的回复后简单地调用您的.each函数。

list(): void { 
this.http.get(`http://localhost:8082/api/list`) 
    .subscribe(response => { 
     this.c= response.json().data; 
     // Your jQuery code goes here 
     $('.carousel').carousel(); 
     $('.carousel .item').each() .... 
    }, error => { 
     this.error = error; 
    }) 
} 
+2

我认为它不会工作,因为我们需要等到更改检测完成后才能在'* ngFor' – yurzui

1

使用信号量;

有一个全局变量switch;

this.http.get(`http://localhost:8082/api/list`) 
    .subscribe(response => { 
     switch = 1; 
     this.c= response.json().data; 
    }, error => { 
     switch = 1; 
     this.error = error; 
    }) 

ngAfterViewInit() { 
    while(!switch) { 
    } 
    $('.carousel .item').each(... 
} 

并保持每个方法的执行不会发生这样一个小的延迟循环,直到异步调用结束它。而不是一个全局变量,你可以使用一些DOM元素来做到这一点还,你的选择〜