user1955726 user1955726 - 5 months ago 14
AngularJS Question

angular factory return data remained same after changing the json file

i am calling a camera.json file from "cameraData" service and injecting the cameradata service in to "CameraController". If i change the camera.json after clicked on refresh button i am getting old data. Any idea?

.factory('cameraData', function ($http, $q,globalVariable) {
var deferred = $q.defer();

var cameraData = {};
var contentType = "application/json; charset=utf-8";

cameraData.GetItemList = function(){
$('.loader').show();
var senddata ={};
senddata.installedcameraid = "9547857793457943";
$http({
//url: globalVariable.ServerAddress + "Admin_GetCameraPoints",
url: globalVariable.Camerafilepath,
dataType: 'json',
method: "POST",
data: JSON.stringify(senddata),
headers: {
"Content-Type": contentType,
"access_token": globalVariable.TOKEN
}

}).success(function(response){
//$scope.response = response;
deferred.resolve(response);
return deferred.promise;

}).error(function(error){
//$scope.error = error;
deferred.reject(error);
});


return deferred.promise;
}


return cameraData;


})

.controller('CameraController',function($scope,$timeout,cameraData){
$scope.refreshCameraData = function(){

$scope.allCamera = [];
cameraData.GetItemList()
.then(function(data) {
$scope.allCamera = data.Camera;
}, function(err) {
// promise rejected, could log the error
console.log('error', err);
});

}

cameraData.GetItemList()
.then(function(data) {
$scope.allCamera = data.Camera;
}, function(err) {
// promise rejected, could log the error
console.log('error', err);
});


})

Answer

You need to create defer object everytime you call factory method. It should return new promise everytime you call api. Change your factory code with following.

var cameraData = {};
$('.loader').show();        
var contentType  = "application/json; charset=utf-8";   

cameraData.GetItemList = function(){
    // need to create defer object everytime 
    var deferred = $q.defer(); 
    $('.loader').show();
    var senddata ={};
    senddata.installedcameraid = "9547857793457943";
      $http({
        //url: globalVariable.ServerAddress + "Admin_GetCameraPoints",
        url: globalVariable.Camerafilepath,
        dataType: 'json',
        method: "POST",
        data: JSON.stringify(senddata),
        headers: {
            "Content-Type": contentType,
            "access_token": globalVariable.TOKEN
        }

    }).success(function(response){ 
        //$scope.response = response;
        $('.loader').hide();
        deferred.resolve(response);
        return deferred.promise;

    }).error(function(error){
        //$scope.error = error;
        $('.loader').hide();
        deferred.reject(error);
    });


    return deferred.promise;
}


return cameraData;
})