AngularJS承诺返回空对象 [英] AngularJS promise returning empty object
问题描述
基本上我想要做的,就是从分配函数调用解析承诺一定借鉴价值。像这样
Basically what I want to do, is to assign some model value from function call that resolves promise. Like so
value = someFun()
这是我从中调用此功能的服务
This is a service from which I call this function
app.factory('SomeService', function($q) {
return {
someFun: function() {
var d = $q.defer();
try {
d.resolve("hi");
} catch (e) {
d.reject(e);
}
return d.promise.then(function(text){
return text;
});
}
};
});
下面是HTML code
Here is the HTML code
<div ng-init="value = 'yes'">
<pre>{{value |json}}</pre>
</div>
<button type="button" ng-click="value = someFun()">click me</button>
这是在控制器
$scope.someFun = SomeService.someFun;
下面是plnkr
http://plnkr.co/edit/qO5ofBXZDsi3cS3bBnT8
现在它返回一个空的对象。什么是错的?
Right now it returns an empty object. What is wrong?
编辑:正如下面已经回答了,是的,这是一种方式,但让我们说,我想打电话给SomeService.someFun在ngRepeat
As already answered below, yes this is one way, but let's say I want to call SomeService.someFun in ngRepeat?
EDIT2:下面是答案 - > <一个href=\"http://stackoverflow.com/questions/25329596/angular-ui-bootstrap-modal-inside-ngrepeat\">Angular里面ngRepeat
推荐答案
一般来说,如果你想使用的东西是异步更新出现在视图中,而无需编写控制器code,以及(这是在的情况下你的问题,你想叫NG-视图中的功能),那么你就需要返回一个空的占位符对象,无论是承诺的结果合并到它,或更新的对象,你可以在引用的属性视图。
Generally if you want to use something that is updated asynchronously to appear in a view without having to write controller code as well (which is the case in your question, as you wanted to call the function inside ng-view), then you need to return a blank placeholder object, and either merge the result of the promise into it, or update a property of that object which you can reference in the view.
您的问题是过于抽象知道处理这个有道理您的应用程序的具体方式,但这里是通用(和抽象的)想法的 plunker这里:
Your question is too abstract to know the exact way to approach this to make sense for your application, but here is the general (and abstracted) idea plunker here:
.factory('promiseService', function($q){
return {
someDeferredThing: function(){
var placeholder = {};
var d = $q.defer();
d.promise.then(function(text){
placeholder.text = text;
});
d.resolve("hi");
return placeholder;
}
}
)
该服务将返回这是由承诺更新的对象,和不可以的承诺本身。如果返回一个承诺,那么你必须处理。然后()
等来获得的价值。
The service returns an object which is updated by the promise, and not a promise itself. If you return a promise then you have to deal with .then()
etc. to get the value.
.controller('appCtrl', function($scope, promiseService){
$scope.deferredResult = promiseService.someDeferredThing();
});
这是你如何分配值的范围。
This is how you assign the value to the scope.
$ scope.deferredResult.text
将不确定,直到承诺解决,那么这将成为定义和解决文字
。因此,您的看法应该处理不确定状态一小段时间 - 通常这是非常简单的事,与 NG-节目
$scope.deferredResult.text
will be undefined until the promise resolves, then it will become defined and resolve to "text"
. As such, your view should handle the undefined state for a short duration - usually it's very simple to do that with ng-show
.
这篇关于AngularJS承诺返回空对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!