空数组承诺

时间:2019-06-12 07:46:30

标签: javascript arrays angularjs promise

我在填充数组时遇到问题,它返回所有空值。我需要基于一些参数通过$ http.get从api服务中获取userList数组。然后,使用此数组,我需要根据预先选择的ID来显示所选用户的名称

在我的service.js中

docx4j-ImportXHTML
 this.getUserStateList = function (val) {
        var url = "/api/v1/hello/getusers";
        var params = { Id: val.Id, SettingId: val.SettingId };
        var config = { params: params };

        var deferred = $q.defer();
        $http.get(url, config, {})
            .success(function (data) {
                deferred.resolve(data);
            }).error(function (msg, code) {
                $log.error(msg, code);
                deferred.reject(msg);
            });
        return deferred.promise;
    };


 this.getUserList = function (val) {
        var usersObj = [];
          this.getUserStateList(val).then(function (data) {
                angular.forEach(data, function (key, value) {
                    angular.forEach(key, function (k, index) {
                     usersObj[index] = ({ userId: k.userId, name: k.name });
                   });
                });
            })

        return usersObj;
    };

在我的控制器中,我打电话给helloservice以获取所选的用户名


  this.getSelectedUserName = async function (id, param) {
        var name = "";
        var userList = await this.getUserList(param);
        console.log(userList);// the array return is empty
        angular.forEach(userList, function (value, key) {
            if (value.userId == id)
                name = value.userId;
        });
        return name;
    }


 var params = { Id: $scope.Id, SettingId: $scope.SettingId };
 $scope.selectedUserName = helloService.getSelectedUserName($scope.UserId, params);

0 个答案:

没有答案