简体   繁体   English

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

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

I have the following angular2 component, which makes an ajax call (with Jquery) and sets the template html to the value of the result: 我有以下angular2组件,该组件进行ajax调用(使用Jquery)并将模板html设置为结果的值:

NB: I am using 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();
    }
}

How can I neatly modify this to make an additional ajax call (to a different url) and set a different property to this? 我如何整齐地修改此属性以进行其他ajax调用(针对不同的url)并为此设置不同的属性? I could create a different sub and then have a complete set of new class properties and then set a new subscription etc. ie twice the number of lines I currently have. 我可以创建一个不同的子类,然后具有一组完整的新类属性,然后设置新的订阅等。即,我当前拥有的行数是原来的两倍。 This isn't a nice way of doing it if I have to make 5+ calls, can I reuse some of the logic and tidy this proposal up? 如果我必须打5个以上电话,这不是一个好方法,我可以重用一些逻辑并整理这个建议吗?

You can create an array of URL's to request, use $.when() , $.map() , .then() , $.each() to process returned response 您可以创建网址的数组要求,使用$.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 plnkr http://plnkr.co/edit/VYwE9Xo4LQh352MlH2yW?p=preview

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

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