Angularjs 将函数转换为角度承诺,以便$scope.*不是未定义的
试图缩小我的代码,以便您清楚地看到我想要完成但没有成功的内容 我想要完成的是当我执行Angularjs 将函数转换为角度承诺,以便$scope.*不是未定义的,angularjs,asynchronous,angular-promise,Angularjs,Asynchronous,Angular Promise,试图缩小我的代码,以便您清楚地看到我想要完成但没有成功的内容 我想要完成的是当我执行console.log($scope.tempData)时我看到的是数据而不是未定义的数据,因此我可以在控制器中使用它。我已经准备好了,因为我在stackoverflow上提出的问题,我知道承诺是一条路要走: 但我不知道的是如何从$scope.getCube()获得承诺
console.log($scope.tempData)时代码>我看到的是数据而不是未定义的数据,因此我可以在控制器中使用它。我已经准备好了,因为我在stackoverflow上提出的问题,我知道承诺是一条路要走:
但我不知道的是如何从$scope.getCube()获得承诺这样我就可以执行$scope.getCube().then(函数(数据){…})代码>我发现了这个:但答案对我来说不够清楚
///////////附带问题////////////
我在底部提供的代码是我在Github上找到的,并不是所有的代码对我来说都很清楚:为什么ClientService.dynamic()是一个承诺?this.dynamic=函数(参数)
中没有q.defer
//////////////////////////////////////////////
要更好地阅读代码:
// CONTROLLER
$scope.buildObject = function () {
$scope.getCube(); //
console.log($scope.tempData); //gives undefined, obvious because getCube is not done running yet.
}
$scope.getCube = function () {
promise = ClientService.dynamic(params);
promise.then(function (data) {
$scope.tempData = data[0];
return $scope.tempData;
}
}
/////////////////////////////////////////////////////
// DYNAMIC SERVICE
this.dynamic = function (params) {
return qvCommService.send(createHyperCube).then(function (data) {
}
}
//////////////////////////////////////////////////
// SEND SERVICE
send: function (msg) {
var deferred = $q.defer();
var promise = deferred.promise;
this.socket = new WebSocket(ws://*************);
this.socket.addEventListener('open', function (e) {
deferred.resolve("connected")
});
this.socket.send(angular.toJson(msg))
return promise;
}
基本上,您错过了从getCube
函数返回它应该返回的承诺,在调用getCube
函数时,您需要使用。然后在它上面使用函数。这样您就可以在的成功回调中获得异步计算的值
代码
$scope.getCube = function () {
promise = ClientService.dynamic(params);
promise.then(function (data) {
$scope.tempData = data[0];
return $scope.tempData;
}
return promise; //return promise object
};
$scope.buildObject = function () {
$scope.getCube().then(function(){
console.log($scope.tempData);
})
}
非常好,谢谢!你能解释一下为什么$scope.getCube=function()
或this.dynamic=function()
是一个承诺吗q.defer()
未在此函数中定义?承诺是否以某种方式存在?在这种情况下,从send:function()
send
方法必须使用$http
调用或$q
实现。这就是它工作的原因我确实有一个$q实现。查看我的原始代码send:function(msg){var deferred=$q.deferred();var promise=deferred.promise;
我真的不明白为什么$scope.getCube=function()
或者this.dynamic=function()
成为承诺,因为发送
是一个promise@Peter我强烈建议你通过链接