以下代码是设计的。我尽可能地简化了问题。
我有一个简单的角度服务,可以进行API调用并返回结果:
<thead>
<th><input ng-model="archived.state" type="checkbox"
ng-true-value="'notarchived'" ng-false-value="undefined">Show archived</th>
</th>
<tbody>
<tr ng-repeat="paymentinfo in paymentList | filter:keyword | filter:money | filter:getdate | filter:{state: archived.state}">
<td>{{paymentinfo.date}}</td>
<td ng-click="singlepage(paymentinfo.id)" ><a>{{paymentinfo.name}}</a> </td>
<td>
<div class="grey-flag remark-payment">
<div class="hover-remark">{{paymentinfo.remark}}</div>
</div>
</td>
<td>$ {{paymentinfo.amount}}</td>
<td id="outmouse">
<ul style="list-style: none;" class="gt-reset">
<li class="dropdown changecoursename">
<a class="dropdown-toggle" data-toggle="dropdown">
<span class="tableOperation norlmalstate">Open Course</span>
<span class="tableOperation openedstate">more options</span>
<b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li><a class="tableOperation" ng-click="paymentRemarks()">Remarks</a></li>
<li><a class="tableOperation" ng-click="paymentReturn(paymentinfo)">Return</a></li>
<li><a class="tableOperation" ng-click="paymentDelete(paymentinfo)">Delete</a></li>
</ul>
</li>
</ul>
</td>
</tr>
在我的控制器中,我可以在服务上调用doWork函数并获得如下的良好响应:
doWork = function(reqId) {
return $http.get('/api/dowork/' + reqId).then(function(response) {
return response.data;
}).catch(function(response) {
return $q.reject(response.data);
});
}
mediumRequest = function() {
var req = 'medium';//normally do something hard to derive this value
return this.doWork(req);
}
但是,如果我需要调用一个中间方法来预处理请求,我会得到“无法读取属性”,然后是“未定义”:
myService.doWork('simple').then(function(response){
//do something great with response
});
为什么函数mediumRequest不返回doWork返回给它的promise?
答案 0 :(得分:1)
试试这段代码,你在服务中做错了
var app = angular.module("myApp", [])
.service('myService',function($http,$q){
this.doWork = function(reqId) {
return $http.get('/api/dowork/'+ reqId).then(function(response) {
return response.data;
}).catch(function(response) {
return $q.reject(response.data);
});
};
this.mediumRequest = function() {
var req = 'medium';//normally do something hard to derive this value
return this.doWork(req);
};
})
app.controller("myCtrl", function($scope,$compile,myService) {
myService.doWork('simple').then(function(response){
console.log('b',response)
});
myService.mediumRequest().then(function(response){
console.log('a',response)
});
})
它会起作用
答案 1 :(得分:0)
与大多数事情一样,问题是我的实际服务代码中存在编码错误。我在这个问题中提出的代码将按预期工作。我很欣赏那些提出识别问题方法建议的人。这是我的问题:
我的实际&#34;中间&#34;函数有这个结构:
mediumRequest = function(options) {
//process first option meeting criteria
options.forEach(function (item) {
if(item.meetsCriteria)
{
var req = item.code;
return this.doWork(req);
}
});
}
正如您所看到的,返回实际上只是退出forEach并且实际上从未实际从mediumRequest函数返回。因此错误。
答案 2 :(得分:-2)
您可以尝试使用$ q服务:
{{1}}