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

时间:2016-08-14 15:30:53

标签: javascript jquery ajax node.js angular

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

注意:我正在使用Typescript

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次以上的调用,这不是一个很好的方法,我可以重用一些逻辑并整理这个提议吗?

1 个答案:

答案 0 :(得分:0)

您可以创建要请求的网址数组,使用$.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