繁体   English   中英

使用JQuery和Angular2进行多个Ajax调用的简洁方法

[英]Neat way of making multiple ajax calls with JQuery and Angular2

我有以下angular2组件,该组件进行ajax调用(使用Jquery)并将模板html设置为结果的值:

注意:我正在使用打字稿

import { Component, Input } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
import {SafeResourceUrl} from '@angular/platform-browser';
import { ActivatedRoute } from '@angular/router';
declare var $: any; //Jquery declare

@Component({
    selector: 'codestep',
    template: `<div class="codestep" [innerHTML]="content"></div>`
})
export class codeStepComponent {
    @Input() step: string;
    private sub: Subscription;
    private content: string = '';
    private url: SafeResourceUrl;

    constructor(private route: ActivatedRoute) { }

    ngOnInit() {
        this.sub = this.route.params.subscribe(params => {
            this.content = this.step;
            var that = this;
            var _url = './diff/' + this.step + '.html';
            $.ajax({
                url: _url,
                success: function (result) {
                    that.content = result;
                    console.log("content: " + result);
                }
            });
        });
    }
    ngOnDestroy() {
        this.sub.unsubscribe();
    }
}

我如何整齐地修改此属性以进行其他ajax调用(针对不同的url)并为此设置不同的属性? 我可以创建一个不同的子类,然后具有一组完整的新类属性,然后设置新的订阅等。即,我当前拥有的行数是原来的两倍。 如果我必须打5个以上电话,这不是一个好方法,我可以重用一些逻辑并整理这个建议吗?

您可以创建网址的数组要求,使用$.when() $.map() .then() $.each()来处理返回的响应

var urls = ["a", "b", "c", "d", "e"];

$.when.apply($, $.map(urls, function(curr) {
  return $.ajax("./diff/" + curr + ".html")
}))
.then(function(...response) {
  $.each(response, function(key, value) {
    var result = value.shift();
    // do stuff with returned `result` here
    // e.g., `that.content = result`
  })
});

plnkr http://plnkr.co/edit/VYwE9Xo4LQh352MlH2yW?p=preview

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM