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

Neat way of making multiple ajax calls with JQuery and Angular2

本文关键字:调用 ajax 简洁 方式 JQuery Angular2 使用      更新时间:2023-09-26

我有以下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个以上的电话,这不是一个好方法,我能重用一些逻辑并整理这个提议吗?

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