简体   繁体   English

操纵Promise中的数据并将其返回到服务函数 - AngularJS中

[英]Manipulate data inside a Promise and return it in a service function - AngularJS

I'm having a problem where I can't assign the service return value into a variable. 我遇到了一个问题,我无法将服务返回值分配给变量。 I have two controllers (AddProject and EditProject) and this function was in both of them, and I wanted to make a service to avoid repeating the code. 我有两个控制器(AddProject和EditProject),这两个函数都在这两个中,我想提供服务以避免重复代码。

        ... 
        .service("UserService", function($http) {
        var allUsers;
        var usersPromise = $http.get("/users");
        usersPromise.then(
            function(response) {
                allUsers = response.data.map(function(user) {
                    user._lowername = user.name.toLowerCase();
                    return user;
                });
                console.log(allUsers) //It prints the object array 
                return allUsers;
            },
            function(error) {
                console.log(error);
                return error;
            });

        this.AllUsers = function() {
            return allUsers;
        }
    })

And in my controller I have a variable: (assume that all required injections were made) 在我的控制器中我有一个变量:(假设所有需要的注射都已完成)

self.AllUsers = UserService.AllUsers(); //it is undefined

I tried to use $q but it gets undefined too. 我试图使用$ q,但它也未定义。

The main reason for using promises is to deal with asynchronous calls (like you $http.get()), but you you seem to be trying to use it in a synchronous way. 使用promises的主要原因是处理异步调用(比如你的$ http.get()),但是你似乎试图以同步的方式使用它。 Your service should just return the promise, then your controller should call it and do what it needs to when it resolves: 您的服务应该只返回承诺,然后您的控制器应该调用它并在结算时执行它所需的操作:

.service("UserService", function($http) {
    var allUsers;
    var usersPromise = $http.get("/users");
    usersPromise.then(
            function(response) {
                allUsers = response.data.map(function(user) {
                    user._lowername = user.name.toLowerCase();
                    return user;
                });
                console.log(allUsers) //It prints the object array
                return allUsers;
            },
            function(error) {
                console.log(error);
                return error;
            });

    this.AllUsers = function() {
        return usersPromise;
    };
});

.... ....

UserService.AllUsers().then(function(users) {
    self.AllUsers = users;
});

It is possible to return self-filling array from asynchronous function that will be filled with values later: 可以从异步函数返回自填充数组,稍后将填充值:

    ... 
    .service("UserService", function($http) {
    var allUsers = [];
    var usersPromise = $http.get("/users");
    usersPromise.then(
        function(response) {
            var result = response.data.map(function(user) {
                user._lowername = user.name.toLowerCase();
                return user;
            });
            angular.copy(allUsers, result);
        },
        function(error) {
            console.log(error);
            return error;
        });

    this.AllUsers = function() {
        return allUsers;
    }
})

angular.copy doesn't change the reference to the array when filling it, the returned empty array is updated automatically in view. angular.copy在填充数组时不会更改对数组的引用,返回的空数组会在视图中自动更新。

This trick is particularly used in ngResource $resource . 这个技巧特别用于ngResource $resource

Partial solution (I believe there is a best solution). 部分解决方案(我相信有一个最好的解决方案)。

.service("UserService", function($http) {
    this.AllUsers = function() {
        return $http.get("/users");
    }
})

And I created a function outside the controllers: 我在控制器外创建了一个函数:

function mapUsers(userResponse){
  return userResponse.data.map(function(user) {
      user._lowername = user.name.toLowerCase();
      return user;
  });
}

And in both controllers I call this: 在两个控制器中我称之为:

UserService.AllUsers().then(function(response) {
            self.AllUsers = mapUsers(response);
        });

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

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