在服务中调用$ http.get时,将返回一个空数组

时间:2019-06-11 11:52:22

标签: arrays angularjs service promise

我想从$ http.get生成的数组中获取名称,但是这将返回一个空数组。当我使用控制台时,会看到数组已填充,但是当我在数组内循环以根据id是否等于某个值获取name属性的值时,该数组为空。

在我的控制器中,我有一个服务呼叫,该呼叫将返回名称值。

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

为我服务

I have used the getUserList function to populate the list of user in a dropdown and it works by generating the array with the values.

However When i got another page , i want to be able to display the name of the selected user, so I wanted to use the same getUserList function to retrieve the name

this.getUserList = function (val) {
        var usersObj = [];
        var url = "/api/v1/hello/getusers";
        var params = { Id: val.Id, SettingId: val.SettingId };
        var config = { params: params };
        var promise = $http.get(url, config)
            .then(function (response) {
                angular.forEach(response.data, function (key, value) {
                    angular.forEach(key, function (k, index) {
                     usersObj[index] = ({ userId: k.userId, name: k.name});
                  });
                });
            },
          function errorCallback(response) {
                    console.log("Unable to perform get request");
                    throw response;
                });
        var usersList = usersObj;

        return usersObj;

    };


 this.getSelectedUserName = function (id, param) {
        var name = "";
        var userList =this.getUserList(param);



        angular.forEach(userList, function (value, key) {
            if (value.userId == id)
                name = value.name;
        });
        return name;
}


数组长度为0,但是如果我在循环之前执行console.log(userList),数组将显示用户数据列表

 this.getSelectedUserName = function (id, param) {
        var name = "";
        var userList =this.getUserList(param);
        console.log(userList) ;
        angular.forEach(userList, function (value, key) {
            if (value.userId == id)
                name = value.name;
        });
        return name;
}


感谢您的亲切回应。

Please see screenshot

3 个答案:

答案 0 :(得分:1)

这是简单的Javascript,并非特定于Angular。你可以做

userList.forEach(user => {
    if(user.userId === id) {
         name = user.name;
    }
});
return name;

答案 1 :(得分:0)

您可以尝试这样。 这里我们使用的是async await

服务

this.getUserList = function (val) {
        var usersObj = [];
        var url = "/api/v1/hello/getusers";
        var params = { Id: val.Id, SettingId: val.SettingId };
        var config = { params: params };
        return new Promise((resolve, reject) => {
           $http.get(url, config)
            .then(function (response) {
                angular.forEach(response.data, function (key, value) {
                    angular.forEach(key, function (k, index) {
                     usersObj[index] = ({ userId: k.userId, name: k.name});
                  });
                });
            },
            function errorCallback(response) {
                    console.log("Unable to perform get request");
                    throw response;
                });
            var usersList = usersObj;
            resolve(usersObj);
        });
    };


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

让我知道它是否有效。

答案 2 :(得分:0)

编辑: 如果您只想匹配用户数组中的一个ID,则无需循环:

anArray = source.filter(source => source.toLowerCase().indexOf(id) === 0);
or
anObject = source.find(obj => obj.id === id);

这是哪个Angular版本?您的标记表示2. +,但其中有$ scope,即ng1.x

由于您已经拥有数组,为什么不能在视图中使用ngFor。您无需在控件中对它们进行排序。

组件

this.getSelectedUserName = function (id, param) {
    let name = ""; // should be array if you want to add unames to it
    let userList = this.getUserList(param);

    // what is `angular` here? And why loop here? Use ngFor in view.
    angular.forEach(userList, function (value, key) {
       if (value.userId == id){
           name = value.name; // will be overwritten each time
           // should be name.push(value.name); // but loop in view instead
       }
    });
    // this.users = name; // for your original sorted version
    this.users = userList;
}

您认为

<li *ngFor="let user of users; index as i;>
  {{user.name}}
</li>