【发布时间】:2014-11-25 22:44:05
【问题描述】:
我有一个将List<KeyValuePair<string, byte>> 返回到 Angular js 工厂的 web api。然后我使用 ->
<select ng-model="survey.surveyType" class="form-control" id="surveyType">
<option ng-repeat="surveyType in surveyTypes" value="{{surveyType.value}}">{{surveyType.key}}</option>
</select>
这很好用。 Angular 循环并正确显示对象。当与 web api 方法交谈时,我已经像这样配置它 ->
app.factory('Survey', ['$resource', function ($resource) {
return $resource('http://localhost:52133/api/surveyapi/:id', null,
{
'update': { method: 'PUT' },
'getSurveyTypesAsDictionary': { method: 'GET', isArray: true, url: 'http://localhost:52133/api/surveyapi/GetSurveyTypesAsDictionary' }
});
}]);
// fetching the values in my controller
var surveyTypes = Survey.getSurveyTypesAsDictionary();
现在我的问题是这个。我无法循环结果。在控制台中,对象看起来像这样 ->
但是,如果我尝试获取角度数组中的值,则那里什么也没有。例如surveyTypes.length 为 0。
问题。如何使用 JavaScript 使用数组? 谢谢!
编辑:
我试图从 web api 只返回 Dictionary<string, byte>,但我根本没有让它工作。
编辑,对 Sergiu 发表评论:
var promise = Survey.getSurveyTypesAsDictionary();
promise.$promise.then(function (response) {
console.log(response.length);
});
为了使您的建议发挥作用,我必须从对象中获取$promise。这是正确的还是我需要配置我的工厂以使其按照您的语法编写方式工作?
【问题讨论】:
-
getSurveyTypesAsDictionary发出一个异步请求并返回一个promise。您需要使用Survey.getSurveyTypesAsDictionary().then(function(response) { // response can be used here });。 -
感谢 Sergiu,在编辑中提出了后续问题 :)
-
是的,您可以像这样使用原始的
$promise对象,也可以使用文档中描述的 callback 语法:docs.angularjs.org/api/ngResource/service/$resource
标签: javascript angularjs asp.net-web-api angularjs-factory