使用JQuery和Angular2进行多个ajax调用的简洁方式
Neat way of making multiple ajax calls with JQuery and Angular2
我有以下angular2组件,它进行ajax调用(使用Jquery)并将模板html设置为结果的值:
注意:我使用的是Typescriptimport { 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
相关文章:
- 阻止在select2单击时调用ajax
- 调用Ajax并返回响应
- Ajax:只在元素存在的情况下调用Ajax
- PHP,MySQL,AJAX-调用AJAX结果后,Bootstrap CSS样式不会显示
- 调用Ajax内部的函数
- 无法获取属性'的值;拆分'在IE8中调用ajax之后
- 我们如何在Firefox中调用AJAX
- Rails:通过调用Ajax重定向
- Cookie 在 Spotify (Javascript) 中调用 ajax 后未保存
- 通过调用 Ajax 来设置 struts bean 值
- 无法从服务器中的 php 调用 Ajax 函数
- 如何在附加表行时调用 ajax
- 在facebook用户发送邀请请求后调用ajax调用
- 定期调用Ajax
- 调用Ajax生成的表单的值
- 无法调用ajax函数
- 在调用AJAX之后显示ng控制器的内容;作为“;作用
- CSS,Java脚本在php中调用ajax后无法正常工作
- 成功调用AJAX后,Toast Growl不会出现
- 如何在调用AJAX时记录或捕获信息和错误