为什么defered.promise在defered.resolve(myobject)之后的结果与myobject不同
Why is the result of defered.promise after defered.resolve(myobject) not the same as myobject
我相信,这就是导致上一个问题中出现问题的原因。我到处看了看,但我仍然不明白发生了什么。当我登录到控制台时,temp
的值会得到预期的结果1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31
,但当我使用var month = $q.defer()
和month.resolve(temp)
并尝试记录month.promise
的值时,我会得到[Object object]
,而不是与temp相同
这就是预期吗
如果否-我做了什么不正确(这就是为什么我使用$q.delay()以防它是一个因素)
如果是-如何将month.promise
转换为更易消耗的表单?即,如果temp是一个数组,如何将month.promise
作为其中temp[0] = month.promise[0]
下面是我的代码示例,但我所有的控制器&服务可以在这里找到,我基本上只想向我的控制器返回一个数组(或JSON),而不是[Object object]
var month = $q.defer();
$http.get('getMonth.php?date=' + date)
.success(function (data, status, headers, config) {
var temp = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31];
console.log("Temp : " + temp + " !!!");
month.resolve(temp);
//month.resolve(data);
//console.log("data "+data[0]);
console.log("resolved " + month);
console.log("resolved[0] " + month[0]);
console.log("resolved.promise " + month.promise + " !!!");
console.log("resolved.promise[0] " + month.promise[0]);
});
更新
根据下面@CuongLe的建议,我添加了下面的代码,我可以成功地记录我的数据,但当我返回时,我仍然得到[Object object]
var promise = month.promise;
promise.then(
function (data) {
console.log(data);
});
来自文档:
延迟对象的目的是公开关联的Promise实例以及可用于通知任务成功或不成功完成的API。
因此,您应该继续使用成功方法调用then
以获得temp
var promise = month.promise;
promise.then(
function(temp){
console.log(temp);
});
您的服务:
angular.module('testApp', [])
.factory('memberFactory', function ($http, $q) {
var getMonth = function (date) {
var month = $q.defer();
$http.get('getMonth.php?date=' + date)
.success(function (data, status, headers, config) {
var temp = [1, 2, 3, 4, 5, 6, 7,...];
month.resolve(temp);
});
return month.promise;
}
return {
getMonth: getMonth
};
});
控制器:
function myController($scope, memberFactory) {
promise = memberFactory.getMonth("2013-08-01 06:30:00");
promise.then(
function (monthDays) {
console.log("monthDays : " + monthDays + " !!!");
var dates = [];
for (var i = 0; i < monthDays.length; i++) {
if (i % 7 == 0) dates.push([]);
dates[dates.length - 1].push(monthDays[i]);
}
$scope.dates = dates;
});
}
使用然后返回promise的方法:
obj.getMonth = function (date) {
var month = $q.defer();
$http.get('getMonth.php?date=' + date)
.then(function (data, status, headers, config) {
var temp = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31];
month.resolve(temp);
});
return month.promise;
}
- 新的 $.fn.MyObject() 在 IE8 中触发“预期对象”错误
- $(myObject) 内存与 myObject 内存 - 问题
- 为什么defered.promise在defered.resolve(myobject)之后的结果与myobject不同
- Object.create(BaseObject)和util的区别是什么?继承(MyObject BaseObject)
- 如何查看在Worker中发布的原始数据?postMessage(myObject)调用
- Node.js (Express API): req.body.myobject未定义,无法工作
- ScriptSharp: myObject.prototype = new myOtherObject;
- 无法使用$.Defered()对象和$.then()中断递归