I need to send few requests to server and get info from it to write it in an array. Function looks like:
$scope.addInstrument = function(themat) {
$scope.data = '{"func":"addInstrument", "thematerial":"' + themat + '", ';
$scope.data += '"lifespan":"' + $scope.lifespan + '"}';
Server.fetch($scope.data, $rootScope.token).then(function(data) {
return data[0].addinstrument;
})
}
Code in controller which calls function:
for (var i = 0; i < $scope.amount; i ++) {
$scope.inventnum[$scope.inventnum.length] = $scope.addInstrument(themat);
}
angular.forEach($scope.inventnum, function(value) {
alert(value);
})
Function which sends requests to server:
app.service('Server', function (AuthService) {
this.fetch = function (data, token) {
return fetch('http://104.197.58.108:8080', {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
data: data,
token: token
})
})
.then(function(response) {
return response.json()
}).then(function(data) {
if (data.success == false) {
return AuthService.logout();
} else {
return data;
}
})
}
})
After that, it alerts 'undefined' right amount of times. I also tried to assign values to array in the function addInstrument():
$scope.addInstrument = function(themat) {
$scope.data = '{"func":"addInstrument", "thematerial":"' + themat + '", ';
$scope.data += '"lifespan":"' + $scope.lifespan + '"}';
Server.fetch($scope.data, $rootScope.token).then(function(data) {
$scope.inventnum[$scope.inventnum.length] = data[0].addinstrument;
})
}
But in this case there were mistakes like Cannot read property length of undefined.