What is the best way to display service data as soon as it is received using $http, without relying on angular.copy?

My challenge is with a service that is supposed to store specific data loaded from a JSON file and display it on the webpage immediately upon receiving. I attempted to set a $scope variable equal to the data in the service, but the data did not show up right away.

I found success only when using:

angular.copy(response.data, this.animals)
, however, I am puzzled as to why it doesn't work when I use: this.animals = response.data. I am curious to understand why this discrepancy exists.

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 used to populate an HTML table
    $scope.animals = animalService.aniamsl;
});

Answer №1

You're on the wrong track, try this instead:

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 a promise, meaning the data will come asynchronously. Instead of using angular.copy, it's better to handle the promise as demonstrated in the code above.

Update:

Since the variable is populated as a promise and needs to be accessed by other controllers, I recommend using events like $rootScope.emit and $rootScope.on to notify the controllers about the value change once the $http request is complete.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

AngularJS allows for filtering unique values per key and retrieving only the checked items

I am working with an angular object and need to display its records with filtering and sorting functionalities. Additionally, I want to show the unique values per key within the object using checkboxes. I have successfully implemented the record display ...

What is the best way to retrieve the number of clients in a room using socket.io?

I am using socket.io version 1.3.5 My objective is to retrieve the number of clients in a specific room. This is the code implementation I have: socket.on('create or join', function (numClients, room) { socket.join(room); }); ...

React-router-sitemap lacks a definition for 'Require'

According to the official documentation here, this is how the sitemap-builder.js file should be structured: require('babel-register'); const router = require('./router').default; const Sitemap = require('../').default; ( ...

The Jquery datepicker value from UIGRid is not being retrieved when attempting to submit the form

I have implemented a jQuery Datepicker in a UI-Grid cell with the following code: { name: 'RDD', displayName: 'RDD', cellTemplate:'<input type="text" class="datepicker" id="{{row.entity.PartID}}" ng-model="row.entity.RDD" ng ...

Hiding labels using JQuery cannot be concealed

Why isn't this working? -_- The alert is showing, but nothing else happens. <asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeaderContent"> <script type="text/javascript"> if (navigator.userA ...

The elimination function in JavaScript

I've been browsing the Mozilla Developers website, focusing on the concept of the delete operator. In the final section about "Deleting array elements," there are two similar scripts presented, with the only difference being how they modify the array. ...

The challenge with the mousewheel function in THREE.js Editor

Attempting to create a basic scene in the THREE.js Editor. Using the built-in Script editor, all control functions seem to be functioning correctly except for the mousewheel (I've tried mousedown, mousemove, etc.). I even attempted to add a listener ...

What could be causing me to receive two responses from this AJAX request?

Can someone shed light on why I am receiving a double success response from this AJAX call using Bootstrap modals? Instead of getting test, I am seeing testtest. After inspecting the console, it appears that only one request is being made and I've c ...

Combine theme configuration options within Material-UI

I am interested in setting up custom theme rules in Material-UI. My goal is to create both light and dark themes and extend them with some shared settings. My initial idea was to store the common settings for the light and dark themes in a separate variab ...

Utilizing jQuery's load method to insert content into a div

My goal is to dynamically load the contents from external HTML files into a div called rightcontent on my webpage using jQuery's load method. Initially, the rightcontent div is empty, but as users interact with links on the page, text should be loaded ...

Exploring the process of passing parameters in Material-UI React styled components

Recently, I developed a new component const CategoryDialog = (props) => { const classes = useStyles(); console.log(props); return ( <div> <Dialog fullScreen open={props.dilaogOpenProp} TransitionCompone ...

Tips on reducing the number of "$routeProvider.when" statements in a complex application

Is there a more efficient way to handle routing in AngularJS, specifically for loading html templates based on $location.path? My current approach involves a long list of "Whens" that will become unmanageable as my application grows. .config(['$rout ...

Clicking on a row in ng2-smart-table should result in the row being

I have attempted to address the issue, but I am struggling to highlight a row on click event. <ng2-smart-table [settings]="settingsPatient" [source]="sourcePatient" (userRowSelect)="patientStudy($event)" (deleteConfirm)="onDeleteConfirm($event)">" ...

Tips for retrieving all JavaScript source links from a website URL during page download

Is there a way to determine if a website is using a specific online JavaScript source, such as fontawesome? Some sources may only become apparent once they are actually loaded, rather than being visible in the website's source HTML. I attempted to us ...

"Experience the power of MVC single page CRUD operations paired with dynamic grid functionality

Currently attempting to create a single page application CRUD functionality using UI Grid, however encountering an error during post request. ...

JavaScript does not display checkbox values

I am currently testing whether checkbox values appear on the client side. When I execute the code, the alert is not showing anything. I would greatly appreciate any assistance, thank you. <div> <label name="finishing"class=" ...

Modify button color once the success callback function has been triggered in Ionic/Angular 2

As a newcomer to programming, I am embarking on the journey of building an Ionic app to send commands to an Arduino via Bluetooth. <ion-content padding> <div padding> <div ion-button clear block medium> <a ion-bu ...

Chrome throwing Dom Mutation warnings related to Angular violations

Recently in our Angular 6 project, I've started noticing some unexpected [Violation] warnings showing up in Chrome. These warnings seem to be originating from line 1666 of zone.js with the message: [Violation] Added synchronous DOM mutation listener ...

Encountering an error while setting up the object spread operator Babel plugin for ES201

Exploring the possibilities of the new ES2018 spread operator for objects led me to discovering a promising NPM package: babel-plugin-transform-object-rest-spread Here's a glimpse of my package.json: // Scripts section "scripts": { "dev": " ...

What is causing my array of objects to constantly accumulate undefined elements?

My quick sort function implementation for the object users_total_likes is behaving unexpectedly. When compiled and run in the terminal or browser, it adds undefined values causing a TypeError: if(users[i][key] >= users[hi][key] && users[j][key] ...