0

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.

Almira
  • 63
  • 5
  • You should avoid resolving promises in the controller. Use the router for resolves. In any case, see if this questions helps http://stackoverflow.com/questions/21177582/directive-is-being-rendered-before-promise-is-resolved – elclanrs Jul 04 '16 at 15:41
  • I think there is one typo also.Serve service is written Server in addInstrument method. – Vivek Singh Jul 04 '16 at 15:45
  • @VivekSingh, thanks. I copied wrong part of code – Almira Jul 04 '16 at 15:51

0 Answers0