2017-03-02 14 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要素を使用して、セマフォを使用して、非同期呼び出しからの応答を取得したり、グローバル変数やDOM要素を変更したり、 'each'関数の前に、非同期呼び出しがそれを変更した後にのみ続行します。 –

+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(... 
} 

そして、非同期呼び出しが終了するまで、このような小さな遅延ループで各メソッドが実行されないようにしてください。

関連する問題