Transferring Data between Rails and Angularjs using JSON

Utilizing Angularjs to fetch JSON data from a Rails test app deployed on Heroku is proving to be a bit challenging. Below you can find the snippets of my Angular and Rails code.

An error message displayed in my Firebug console reads: "NetworkError: 404 Not Found - "

Any insights on why this setup isn't functioning correctly?

Angularjs code

var App = angular.module('App', []);

App.controller('TodoCtrl', function($scope, $http) {
  $http.get('http://desolate-earth-2852.herokuapp.com/declarations.json')
       .then(function(res){
          $scope.todos = res.data;        
        });
});

Rails code

  def index
    @declarations = Declaration.all

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @declarations }
    end
  end

Route Configuration

Test::Application.routes.draw do
  root :to => 'welcome#index'
  get "welcome/index"
  resources :declarations
end

Answer №1

One possible reason for the issue could be due to Rails JS minification. This topic is covered by Ryan Bates in his Railscast on integrating AngularJS. It appears that you haven't accounted for minification in your configuration files, which means all Dependency Injection in your Angular code should be structured within an array like the example below:

App.controller('TodoCtrl', ['$scope', '$http', function($scope, $http) {
  $http.get('http://desolate-earth-2852.herokuapp.com/declarations.json')
    .then(function(res){
       $scope.todos = res.data;        
    });
}]);

As opposed to this approach:

App.controller('TodoCtrl', function($scope, $http) {
  $http.get('http://desolate-earth-2852.herokuapp.com/declarations.json')
   .then(function(res){
      $scope.todos = res.data;        
   });
});

By specifying dependencies in an array, AngularJS can properly handle changes in names during minification without any issues. This practice should be applied to every function that utilizes services, such as the controller creation function demonstrated here.

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

Trouble with Angular Charts: Data Reading Issue

Trying out chart.js for the first time and encountered an issue where the chart is not able to read data from the model. Previously, I had an error message of Error: $injector:modulerr Module Failed to instantiate module chart.js. This was fixed by switch ...

Stop receiving notifications for channel events in Stream with the GetStream.io Chat API

I'm having trouble understanding how to stop listening for channel events in JavaScript using the Stream Chat API. According to the documentation: // remove the handler for all "message.new" events on the channel channel.off("message.new", myChanne ...

Vue Deep Watcher fails to activate when the data is altered

While the countdown timer is functioning properly, it seems that the deep watcher is not working as expected. Despite attempting to log the new value of seconds in the console, it does not display anything even though the countdown timer continues to funct ...

Acquire information using Vue through HTTP requests based on Router parameters

I have been searching for a solution to this issue and even referred to the example provided on the Vue Router documentation, but I am still encountering difficulties. My goal is to make an HTTP call when a component loads initially, then monitor the route ...

Connected with the functionalities of Umbraco Forms

Looking to develop a plugin similar to Umbraco Forms with identical functionality. Is it possible to incorporate custom fields from a database into the Umbraco backend's custom section and have them displayed on the frontend like Umbraco Forms? Seekin ...

Customize the appearance of the Vue.js datepicker starting from today's date

I am currently using the vue-datepicker component to display a date input field in my form. I want to set the default date to the current day and disable the selection of past dates. Additionally, I need to change the language of the component but it seems ...

After the data has finished loading, AngularJS will apply the directive to each select tag every time

I have created a directive that needs to be applied on each 'select' tag, but because it involves parsing the select data, it should be done after the data has been loaded. Unfortunately, the code I wrote only works on the last select item: ...

What are the steps to setting up Webpack-simple with Vue Cli 3?

I'm completely new to Vue Cli and the Vue framework in general, so any help is appreciated! From what I understand, in Vue Cli 2, the command was something like this: Vue init webpack-simple xxx However, with the latest major update (3), it has cha ...

Guide to Repairing Uncaught TypeError: players.setAttribute is not a recognized method?

I'm a beginner and encountered an error saying Uncaught TypeError: players.setAttribute is not a function when submitting an action. How can I solve this issue? Please share your insights. ''' //selecting all necessary elements const s ...

Tips for properly formatting the sort_by parameter in Cloudinary to avoid errors

Greetings to the helpful stack overflow community, I have encountered an issue with fetching images from cloudinary via a post request. Everything works fine until I include the sort_by parameter in the URL. This results in an error related to the format ...

What is the best way to connect an external JSON file to an Angular controller?

As I embark on my first Angular JS project, I find myself in need of exporting a JSON array from my controller to an external JSON file. Here is the snippet from my controller containing the JSON data: Fantacalcio.controller('fantacalcioController&ap ...

Creating a bot that will only respond once when a user sends multiple photos simultaneously

I'm currently working on a Telegram bot using nodejs. I am utilizing the node-telegram-bot-api library and have implemented the on('photo') method to handle when a user sends a photo to my bot. However, I am facing an issue where if a user ...

How to use jquery and ajax to retrieve an array of data and show it on the screen

I am facing an issue with my ajax request. Actually, I am unsure of how to fetch multiple records. I attempted the following: $rqt = "SELECT a,b,c from table"; $res = mysql_query($rqt); while ($data = mysql_fetch_assoc($res)): $objet = $d ...

What is the maximum size allowed for arrays in QJson?

Currently, I'm working on a project using QT 5.5 where I am receiving a JSON object via QNetwork that I need to parse. The JSON structure of the object looks like this : { "cas_version":1008, "result":"true", "diaporamas": { "0": ...

A single Rails route that serves up distinct queries in both HTML and JSON formats

In the controller, I have a basic index action that serves both HTML and JSON formats. def index @records = Model.all respond_to do |format| format.html format.json { render json: @records } end end Recently, I revamped the HTML view usin ...

Simple HTML files on a local server are having trouble loading images and JavaScript, yet the CSS is loading

Having worked in web design for quite some time, I recently began working on a basic Angular app that is meant to be very simple. For this project, I am only using the angular files and a single html file as the foundation. As I started setting up the bas ...

Asynchronous Task paired with JSON, the onSuccess method fails to provide any returns

Here is my query: I'm facing an issue with the code in my AsyncTask function that fetches values from a JSONObject through a webservice. Despite successfully filling a List with data from the JSON in the onSuccess method, the "result" turns out to be ...

Discovering the world of Javascript and JQuery by diving into the intricacies of

Similar Question: Formatting dates using Javascript I have recently started working with JavaScript and jQuery. I am currently experimenting with creating a page that retrieves data from a public Google calendar and displays the events, including star ...

The socket.rooms value is updated before the disconnection listener finishes its process

When dealing with the "disconnect" listener, it's known that access to socket.rooms is restricted. However, I encountered an issue with my "disconnecting" listener. After making some modifications to my database within this callback, I attempted to em ...

ScriptManager is not accessible in the current ASP.Net Core Razor Page context

I'm facing an issue where I have a view (such as Index.cshtml) and a page model (like Index.cshtml.cs). In the view, there's a JavaScript function that I want to call from the OnPost() method in the page model. I tried using ScriptManager for thi ...