【问题标题】:Execute Jquery after asynchronous task [duplicate]在异步任务后执行 Jquery [重复]
【发布时间】:2017-03-02 15:34:46
【问题描述】:

初始化轮播后,我想在 jQuery 中执行“每个”函数。但是,在 ngOnInit() 函数上,我有一个与 http.get 的异步任务来获取初始化轮播所需的数据。

我的代码:

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

每个函数都没有执行...

【问题讨论】:

  • 使用信号量,在你得到异步调用的响应后,修改一些全局变量,或者一些DOM元素,并在each函数之前不断检查,只有在异步调用修改它之后才继续。
  • 从您的异步方法初始化回调中的轮播。

标签: jquery angular typescript


【解决方案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 元素来执行此操作,您可以选择~

【讨论】:

    【解决方案2】:

    这是因为您的异步函数的响应尚未出现。收到回复后,您只需调用 .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;
        })
     } 
    

    【讨论】:

    • 我认为这行不通,因为我们需要等到更改检测完成呈现 *ngFor 中的项目后才能使用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多