2

I want to execute a "each" function in jQuery, after initializing my carousel. But, on ngOnInit() function, I have an asynchonous task with http.get to get data I need to initialize the carousel.

My code :

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));
        }
    });
}

The each function is not execute...

  • Use a semaphore, after you got response from the async call, modify some global variable, or some DOM element, and check that continuously before `each` function, continue only after async call modifies it. – buræquete Mar 02 '17 at 15:37
  • initialise the carousel inside the callback from your asynchronous method. – ADyson Mar 02 '17 at 15:40

2 Answers2

1

This is because the response from your async function is not there yet. You can simply call your .each function after receiving your response.

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
    I think it won't work because we need to wait until change detection finished rendering items within `*ngFor` – yurzui Mar 02 '17 at 15:42
1

Use a semaphore;

have a global switch variable;

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

And keep each method execution from happening with such a small delaying loop until async call ends it. Rather than a global variable, you can use some DOM element to do this also, your choice~

buræquete
  • 14,226
  • 4
  • 44
  • 89