AngularJS doesn't fetch JSON data

I am attempting to retrieve data from a JSON file using AngularJS and the $http.get method. I am following the new way of writing AngularJS scripts, as outlined in this helpful link.

PLUNKER

However, when I try to execute my code, nothing appears to be happening and Firebug is not providing any useful information.

I suspect that the issue lies within my activate() function, particularly with regards to my understanding of promises.

function activate() {
    return $http.get('test.json').then(function(data) {
        vm.result = data;
        return vm.result;
    });
} 

Do you have any insights or suggestions on how to resolve this issue?

Answer №1

Upon reviewing the provided information, a couple of issues have been identified.

Initially, in the plunker code snippet, there is an overlooked detail:

controller.$inject = ["$http"];

function controller() {

The omission of the $http parameter in the controller function's signature has been noted.

function controller($http) {

Furthermore, upon correction, it was observed that the index.html file was binding to {{c.value}}, but no such property was defined in the controller. Perhaps it should be {{c.result}}? By making these adjustments, a visible outcome can be achieved.

Answer №2

At this particular moment in your code, you are unable to use the return statement within your then callback function. Instead, you should return the `$http` call itself, which will be a promise that needs to be resolved. Additionally, if you see an error message in your console saying something like `$http is undefined`, it indicates that the service was not injected properly. Take a look at the example below...

function activate() {
    return $http.get('test.json')
}

[...]

activate().then(function(response) {
    vm.result = response.data;
});

Plunker - see demo


On another note, it would be beneficial to encapsulate the logic of the `activate()` function into a reusable service to avoid cluttering your controllers. Therefore, instead of directly injecting `$http`, inject the custom service into the controller.

Plunker - demo showcasing logic wrapped in a simple service

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

In Angular JS, you can seamlessly apply the addClass function to another element by simply hovering over one

Trying to achieve the desired outcome using jQuery but facing issues in an Angular environment. It seems that I might be working outside of the Angular JS scope, and being new to Angular, I'm unsure how to implement this using Angular's scope met ...

What is the best way to merge two objects from separate arrays without losing any of their values?

While the current code functions well for a single record, I am seeking to adapt it to handle an array containing approximately 500 records... var aaa = { aaa_id: 123, abbr_name: "j_doe", name: "john doe" } var bbb = { bbb_id: 789, } for ...

Custom template for prefetched data is not displaying in Typeahead.js

I'm currently utilizing Twitter's typeahead.js plugin for displaying autocomplete suggestions. Here is the code snippet: $.ajax({ url:'/getlocals/', success: function(data){ $('.local-type').typeahead({ ...

jquery, slideToggle not behaving correctly on mouse hover

Whenever the mouse hovers over my div with the class .frame, I slideToggle a div with the class .content. And when the mouse leaves .frame, I toggle .content back again. Everything seems to be working fine except for two issues: the effect gets messed up i ...

eliminate empty lines from csv files during the uploading process in Angular

I have implemented a csv-reader directive that allows users to upload a CSV file. However, I have noticed an issue when uploading a file with spaces between words, resulting in blank lines being displayed. Here is an example: var reader = new FileReader ...

What is the method employed by the script to ascertain the value of n within the function(n)?

I've recently started learning about jQuery. I came across a program online that uses a function where the value of n starts from 0 and goes up to the total number of elements. In the example below, there is only one img element and jQuery targets thi ...

Display the content of a Vue file directly on the webpage

I am currently developing a website to showcase UI components using plain CSS. The project is built with Vue, utilizing standard HTML and CSS. One of the key features I am working on is providing users with two views for each component: 'Preview' ...

Spring Boot is having trouble identifying the JavaScript files

I've incorporated Spring Boot in my project and I'm working with a JSP file that looks like this: <%@ include file="common/header.jsp" %> <%@ include file="common/navigation.jsp" %> <div class="container"> ...

The scrolling function halts as soon as the element that was middle-clicked is deleted from the

I am knee-deep in developing my own React virtualization feature and encountering a minor annoyance. When I middle click on an item in the list and start scrolling, the scrolling stops once that item is removed from the DOM. My initial thought was that the ...

Trouble locating alias path with Jest

I have recently implemented an alias path to streamline the import of components in my project. Instead of using long relative paths like ../../../../componentFolder, I now use @src/componentFolder. However, this change has caused my unit tests to fail as ...

How can a dialog be displayed using a template in Onsen UI in a proper manner?

I am having trouble displaying a dialog in my Angular app with Onsen UI 1.3.6. Whenever I try to show the dialog, I encounter a 404 Not Found error. This is the JavaScript code I am using: ons.createDialog('iconselector.html').then(function(dl ...

What is the best way to achieve line breaks in text that auto-wraps in JavaScript/PHP?

My resizable div contains text/sentences. As I adjust the size of the div, the text wraps itself to perfectly fit within the available space in the container div. Now, I am faced with the task of converting this dynamic text into an image using php and th ...

The submitHandler for AJAX does not function properly when using bootstrapvalidator

I'm encountering an issue with the Bootstrap validation tool found at https://github.com/nghuuphuoc/bootstrapvalidator The submitHandler function seems to be malfunctioning for me. Upon form submission, the entry is not being created and the form rel ...

Looking to add a button on a PolymerJS page that will allow users to download a PDF file of the report in a row-by-row

I am looking to add a button to a polymerJS webpage that, when clicked, will download a PDF with decorations in a table format containing rows and columns. Can someone guide me on how to achieve this? Thank you in advance. ...

Issue with parsing object in ejs template file

Currently, I am in the process of creating a movie database using MongoDB, node.js, and express. There are two routes set up - one that displays all movies in the database on a page, and another that shows information for an individual movie. The issue ari ...

Tips for positioning a div relative to another div while controlling its z-index

Hey there, take a look at the image below https://i.sstatic.net/zYiaY.png The issue I'm facing is quite common - I have div 1 and div 2 visible in a loop, but divs 3 are hidden. When div 2 is clicked on, everything is great so far. However, what I wa ...

What's the best way to extract a JSON string from a specific URL?

Looking to store JSON data in an array: arr[ ] array = {"http://www.ip-api.com/json"}; How can I print the JSON data itself instead of just showing "" as a string? ...

A guide on transferring the text box value to a disabled text box with javascript

Currently, I am working on a text box where users can enter a value. I would like to dynamically update another disabled text box with the entered value using JavaScript. Regards, Vara Prasad.M ...

Utilizing lazy evaluation, multiple functions are triggered by ng-click in succession

Successfully disabled ngClick on an element when the scope variable (notInProgress) is set to true as shown below: <a data-ng-click="notInProgress || $ctrl.setTab('renewal');</a> Now, I want to include additional functions to be execut ...

What is the best way to retrieve HTTP tags within a map function in React?

I'm currently working on a dynamic bar chart with multiple levels. I utilized the map function to generate the chart data and did console logging to ensure everything is in order. However, despite the code working properly, the return tag doesn't ...