我有这样的工作代码:
服务(工厂?):
myApp.factory('MyService', ['$q','$resource', 'MyResource',
function ($q, $resource, MyResource) {
return {
getRoles: function () {
return MyResource.getRoles(); //MyResource makes API calls using $resource
} } });
控制器:
$scope.Roles = MyService.getRoles();
$scope.Roles.$promise.then(function () { $scope.RolesCount = $scope.Roles.length; });
我想做的是在MyService中创建此类功能,该功能将在解决Getroles时返回角色数量,以便我可以在控制器中使用它:
$scope.RolesCount = MyService.getRolesCount();
,然后在html
中{{RolesCount}}
不幸的是,我不知道该怎么做,因为我的getRolescount()方法需要返回某些东西,以便我在myService中无法使用$ promise..then()。提出更准确的内容后,我会尝试更新问题的标题。
如果需要在服务中转换服务器响应,则应将then
移至此处。但是,如果then
应该解开承诺并为范围分配一个值,则不可行,也不可能。
$resource
返回一个以承诺分辨率填充的对象。应该使用资源的方式是:
{{Roles.length}}
当对象更新时,它也将在查看中进行更新。将值分配给另一个变量效率低下。
不可能做
之类的事情$scope.RolesCount = MyService.getRolesCount();
因为 getRolesCount
是异步的,并且它与is caligar一起解析的值。如本答案所述,可以用`rasync..Wawait(Typescript或ES2017)将其弄平。