2017-03-02 137 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元素來做到這一點還,你的選擇〜