简体   繁体   English

解决 $resource promise 后从服务返回值

[英]Return value from service once $resource promise is resolved

I have such working code:我有这样的工作代码:

Service (factory?):服务(工厂?):

myApp.factory('MyService', ['$q','$resource', 'MyResource',
    function ($q, $resource, MyResource) {

        return {
            getRoles: function () {
                return MyResource.getRoles(); //MyResource makes API calls using $resource 
            } } });

Controller:控制器:

$scope.Roles = MyService.getRoles();
$scope.Roles.$promise.then(function () { $scope.RolesCount = $scope.Roles.length; });

What I'd like to do is to create such function in MyService that will return number of roles once getRoles is resolved so I can use it in controller like this:我想要做的是在 MyService 中创建这样的函数,一旦 getRoles 被解析,它将返回角色数,以便我可以在控制器中使用它,如下所示:

$scope.RolesCount = MyService.getRolesCount();

and then in html然后在 html 中

{{RolesCount}}

Unfortunately, I have no idea how to do this since my getRolesCount() method needs to return something so I can't use $promise.then() inside MyService.不幸的是,我不知道该怎么做,因为我的 getRolesCount() 方法需要返回一些东西,所以我不能在 MyService 中使用 $promise.then()。 I'll try to update my question's title once I come up with something more accurate.一旦我想出更准确的东西,我会尝试更新我的问题的标题。

If server response needs to be transformed in a service, then then should be moved there.如果在服务转化服务器响应的需求,然后then应该有感动。 However, it's not practical or possible if then is supposed to unwrap a promise and assign a value to scope, like in the code above.但是,如果then应该像上面的代码那样解开承诺并为作用域分配一个值,这是不切实际或不可能的。

$resource returns an object that is filled on promise resolution. $resource返回一个在承诺解析时填充的对象。 The way a resource is supposed to be used in view is:在视图中应该使用资源的方式是:

{{Roles.length}}

When an object is updated, it will be updated in view, too.当一个对象被更新时,它也会在视图中更新。 Assigning the value to another variable is inefficient.将值分配给另一个变量是低效的。

It's impossible to do something like做这样的事情是不可能的

$scope.RolesCount = MyService.getRolesCount();

because getRolesCount is asynchronous, and the value it resolves with is scalar.因为getRolesCount是异步的,它解析的值是标量。 It is possible to flatten it with `async..await, (TypeScript or ES2017), but will require additional measures to synchronize control flow with AngularJS digests, as explained in this answer .可以使用 `async..await(TypeScript 或 ES2017)将其展平,但需要额外的措施来同步控制流与 AngularJS 摘要,如本答案中所述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM