Chain two calls to $ resource to update two related entities

0

I have two related entities (Expedition and Temperature) and I need to keep the temperature when I create a new expedition.

This is the code that I currently have:

angular.module('nowLocateApp').controller('ExpedicionDialogController',
['$scope', '$stateParams', '$uibModalInstance', 'entity',     'Expedicion', 'Camion', 'Delegacion',
    function($scope, $stateParams, $uibModalInstance, entity,   Expedicion, Camion, Delegacion,Temperatura) {

    $scope.expedicion = entity;
    $scope.camions = Camion.query();
    $scope.delegacions = Delegacion.query();
    $scope.load = function(id) {
        Expedicion.get({id : id}, function(result) {
            $scope.expedicion = result;
        });
    };
   $scope.save = function () {
        $scope.isSaving = true;
        if ($scope.expedicion.id != null) {
            Expedicion.update($scope.expedicion, onSaveSuccess, onSaveError);
        } else {
            Expedicion.save($scope.expedicion, onSaveSuccess, onSaveError);
            $scope.temperatura.expedicion = $scope.expedicion.id;
            $scope.temperatura.temperatura = 10;
            Temperatura.save($scope.temperatura);
        }
    };

}]);

You can see in full code is my repository of GitHub, I hope you can help me.

link

    
asked by alex molero 30.04.2016 в 13:10
source

1 answer

0

What you need is to chain two calls to $ resource to update two related entities (Expedition and Temperature) because you need the unique identifier of the new Expedition in order to save the temperature.

To do this you have to use the result of the save method and access the promise with $promise

$scope.save = function () {
    $scope.isSaving = true;
    if ($scope.expedicion.id != null) {
        Expedicion.update($scope.expedicion, onSaveSuccess, onSaveError);
    } else {
        var saveResult = Expedicion.save($scope.expedicion, onSaveSuccess, onSaveError);
        saveResult.$promise.then(function(savedData) {
            $scope.temperatura.expedicion = savedData.id;
            $scope.temperatura.temperatura = 10;
            Temperatura.save($scope.temperatura);
        });
    }
};
    
answered by 01.05.2016 / 21:49
source