【发布时间】:2017-03-11 08:30:25
【问题描述】:
嗨,页面上有 4 个指令,所有指令都需要用户列表。 用户列表存储在需要 hhtp 请求的数据库中。 由于页面上同时存在 4 个指令,因此已将 4 个不同的 ajax 调用发送到服务器以获得类似的响应。
然后响应被缓存。
可以做什么,所有 4 个指令都接收到它的用户列表,并且只有一个 ajax 被发送到服务器。
指令内的代码(self is this)(ajaxCallService 是服务)
ajaxCallService.getUser(function(response) {
self.users = response;
//Next operations
});
ajaxCallService 服务
Variable
var userList = []
Method
if (!userList.length) {
$http.post({
url: #,
data:#
})
.then(
function(response) {
userList = response.allMembers;
callback && callback(userList);
}
);
}else{
callback && callback(userList);
}
如何防止 4 个 ajax 调用,只进行 1 个调用,让其他 3 个等待响应并返回响应?
【问题讨论】:
-
使用角度承诺。
-
在前一个的回调中调用每个ajax函数。
标签: javascript angularjs angularjs-directive angularjs-service angular-http