Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show service data immediately when it is received with $http without using angular.copy?

I have a service, which should save me the specific data that I load from a JSON file. I want the data to show on the page as soon as it's received. I created a $scope variable to be equal to the data in the service, the data is not shown immediately on the page.

I only achieved my goal when using: angular.copy(response.data, this.animals), but I do not understand why it is not working when I am using: this.animals = response.data. I would like to know why this is happening and what is the difference.

module.service("animalService", function($http) {
    this.animals=[];
    $http.get('animals.json').then(function(response) {
        //this.animals = response.data ----> not working
        angular.copy(response.data, this.animals)
    });
});

module.controller("animalController", function($scope, animalService) {
    //$scope.animals is what I use to create a table in html
    $scope.animals = animalService.aniamsl;
});
like image 301
Noy Gafni Avatar asked Nov 06 '22 17:11

Noy Gafni


1 Answers

You are not doing it right, try:

module.service("animalService", function($http) {
     return $http.get('animals.json')
});

module.controller("animalController", function($scope, animalService) {
    animalService.then(function(res){
       $scope.animals = res.data
    });
});

any http response returns promise, and what it means is that the data would come asynchronously. As per my understanding using angular.copy triggers a digest cycle and so the changes are detected but it's not at all a good practice. Prefer promise handling as I have shown in the above code

Update:

Since the variable is populated as a promise and it is to be used by other controller , I would suggest to use events such as $rootScope.emit and $rootScope.on so that the controllers are notified about the change in value after $http is completed

like image 176
Shashank Vivek Avatar answered Nov 14 '22 15:11

Shashank Vivek