我是 Angular 的新手,现在我已经使用它差不多 2 周了。
我有一个我设法解决的实现问题。问题的概述是我有一个 main.html
显示所有用户信息但未被服务功能更新 this.list
当我尝试使用服务 this.addNewUser
添加新信息时.以下是代码的工作版本和不工作的版本。
虽然我解决了自己的问题,但我还是发帖在这里的原因是我很好奇想知道原因。我想了解 defer 对象 的两个示例之间的区别。第二个示例不起作用,但第一个示例运行良好。
区别是否与 defer 对象有关,我只能在函数内部声明它?也许我不能全局声明它?
我希望有人能解释为什么第一个示例有效而第二个示例无效。
#1 示例
//Add single user
this.addNewUser = function(username,email){
**var deferred_2 = $q.defer(); //current active object for asyn ajax call**
$http({
method : 'GET',
url : '/app/add.php',
params: {
"name":username,
"email":email,
},
})
.success(function(data, status, headers, config) {
deferred_2.resolve('Success');
})
.error(function(data, status, headers, config) {
console.log('Data :: ' + data);
console.log('Status :: ' + status);
console.log('Config :: ' + config);
});
return deferred_2.promise; //Promise object is the results
}
#2 示例
var deferred_2 = $q.defer(); //current active object for asyn ajax call
//Add single user
this.addNewUser = function(username,email){
$http({
method : 'GET',
url : '/app/add.php',
params: {
"name":username,
"email":email,
},
})
.success(function(data, status, headers, config) {
deferred_2.resolve('Success');
})
.error(function(data, status, headers, config) {
console.log('Data :: ' + data);
console.log('Status :: ' + status);
console.log('Config :: ' + config);
});
return deferred_2.promise; //Promise object is the results
}
我面临的问题是,当我调用另一个如下所示的函数时,它没有更新 main.html
使用服务 this.addNewUser
中的函数刚刚插入的新数据.
//List all user
this.list = function(){
console.log('About to start');
//Get Data
$http({
method : 'GET',
url : '/app/get.php',
})
.success(function(data, status, headers, config) {
deferred_2.resolve(data);
})
.error(function(data, status, headers, config) {
deferred_2.reject("Something bad here");
});
return deferred_2.promise;
}
最佳答案
AngularJS 中的服务是单例的,这意味着全局 deferred_2
已经被你的第一个函数解析(或拒绝)了。
发件人:https://docs.angularjs.org/api/ng/service/ $q
The purpose of the promise object is to allow for interested parties to get access to the result of the deferred task when it completes.
因为延迟任务已经完成,后续将其标记为已解决或拒绝的调用不会触发您附加到第二个 promise 的任何回调。我认为没有任何理由在函数之间共享延迟 - 如果您希望在添加新用户后更新列表,我建议您查看 Angular 的 $emit
, $ broadcast
和 $on
方法用于 $scope
对象上的事件:)
https://stackoverflow.com/questions/23278291/