Failed to load JSON data from the factory

Recently, I started learning AngularJS and have been struggling to fetch JSON data from a factory. The error message I keep getting is not very helpful:

TypeError: Cannot read property '1' of null

This is the module I am working with:

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

Below is my Controller code:

app.controller('homePageController', function ($scope, projectsFactory) {
    $scope.projects = projectsFactory.getList();
});

This is how I defined my Factory:

app.factory('projectsFactory', function($http, $q) {
return {
    getList: function() {
        var deferred = $q.defer();
        $http.get('Resources/JSON/projects.json').success(function(data){
            deferred.resolve(data);
        }).error(function(){
            deferred.reject();
        });
        return deferred.promise;
    },
};
});

Here is part of the HTML page:

<ul ng-controller="homePageController">
<li ng-repeat="project in projects">
    {{projects.name}}
</li>
</ul>

And here is an excerpt from the JSON file:

[
{
    "Id": 1,
    "name": "Colombo Law",
    "snippet": "Colombo Law snippet"
},
{
    "Id": 2,
    "name": "Lunch?",
    "snippet": "What for lunch snippet"
}
]

This is the detailed error message I am seeing:

TypeError: Cannot read property '1' of null
at $get (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.js:6839:28)
at link (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular-route.js:907:26)
at nodeLinkFn (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.js:6271:13)
at compositeLinkFn (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.js:5682:15)
at publicLinkFn (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.js:5587:30)
at boundTranscludeFn (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.js:5701:21)
at controllersBoundTransclude (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.js:6292:18)
at update (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular-route.js:865:25)
at Scope.$get.Scope.$broadcast (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.js:12329:28)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular-route.js:556:26 <div ng-view="" class="ng-scope">

If anyone can provide guidance or assistance with this issue, it would be greatly appreciated!

Answer №1

With newer versions of Angular, promises are not automatically resolved. The factory in your project is returning a promise instead of an actual list, causing the ng-repeat directive to not work on a promise.

To resolve this issue, you can assign the result of the promise to your scope variable by updating your controller code like this:

app.controller('homePageController', function ($scope, projectsFactory) {
  projectsFactory.getList().then(function(projects) {
    $scope.projects = projects;
  });
});

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

Is it possible to capture a Browser TAB click event using JavaScript or AngularJS?

How can I trigger an event when returning to a tab? For instance: Let's say I have opened four tabs in the same browser with the same URL: such as: http://127.0.0.1:/blabla http://127.0.0.1:/blabla http://127.0.0.1:/blabla http://127.0.0.1:/blabla ...

`Javascript often returns NaN for basic calculations`

Hello, I am currently developing a basic calculator for a game but I have encountered an issue. Despite having just started learning this programming language and reading all available tutorials, I am now in the process of writing code to gain more experie ...

"Incorporate an image into the data of an AJAX POST request for a web service invocation

I have been attempting (with no success thus far) to include an image file in my JSON data when making a call to a method in my webservice. I have come across some threads discussing sending just an image, but not integrating an image within a JSON data o ...

A guide on transforming a JSON response into YAML using bash

Having trouble appending data from a json file to a yaml file using jq in shell programming. Trying to add "users" to an existing "users" array in the yaml file. Here is the json file content: #$DEFAULTS_FILE {"users": [ {"name":"pi", "gecos ...

Issues with Angular displaying filter incorrectly

Whenever a user chooses a tag, I want to show only the posts that have that specific tag. For instance, if a user selects the '#C#' tag, only posts with this tag should be displayed. This is how my system is set up: I have an array of blogs that ...

Approaches to Json serialization and data storage

When it comes to web applications, Json is a commonly used format. I have chosen to set a field in the database to store Json strings as text. While some may argue that this is not the best way to design a database, my rationale is that the data's com ...

Next auth does not provide authentication functionality for Firebase

I've implemented next-auth with a firebase adapter, and while everything seems to be functioning properly in terms of saving users in the database, I'm encountering some issues with authentication. import NextAuth from "next-auth" impo ...

Ways to retrieve the complete user object in passport

Recently, I've been diving into utilizing Express authentication with Passport and React for the frontend. While working on this project, a question came up: How can I access the entire authenticated user object? This is what my database model looks l ...

Style the code presented within a div tag

I am in the process of creating a JavaScript-powered user interface that can generate code based on user interactions. While I have successfully implemented the code generation functionality and saved the generated code as a string, I am facing difficultie ...

Tips for passing a distinct identifier to the following page when transitioning with Link in NextJS

I need to pass an identifier to the next page when a user navigates. On my homepage, I am fetching an array of data and using the map method to display it in a card-based UI. When a user clicks on a card, they should be taken to another page that display ...

Unable to store cookie using jQuery on Internet Explorer 9

Having trouble setting a cookie on IE9 and can't figure out why. My objective is to create a cookie that expires after a year, using the code below: $.cookie( name, value, { expires:days } ) where days equals 365. However, the cookie disappears as s ...

When it comes to entering text in a text input or textarea within a large module in Vue.js, taking

While filling out my large form, I noticed a delay in rendering whenever I typed quickly into the input boxes. <b-form-input v-model="paymentItems.tierStepUPYear" type="text"></b-form-input> ...

Is there a way I can utilize a for-loop and if statement in JavaScript to present the information accurately within the table?

My current task involves fetching data via AJAX and then using a for-loop and if-statement to determine which goods belong in each shopping cart. Once identified, I need to display these goods in separate tables corresponding to each customer. Although the ...

Troubleshooting: JavaScript Bookmarklet Fails to Execute on Certain Websites

Recently, I created a unique bookmarklet that functions flawlessly on some websites, but unfortunately fails to work on others. Interestingly, even when it doesn't work, the script is still added to the bottom of the page; however, only a portion of t ...

Retrieve the Multer file name and/or file path

Just checking in on everyone's well-being. I'm currently struggling to retrieve the file path or name after uploading it to the folder. Whenever I try console logging req.files.path or req.files.filenames, it always returns undefined. Could someo ...

What is the most efficient way to utilize AngularJS and Twitter Bootstrap for forms integrated with Rails, while minimizing the amount of code used?

I am looking to streamline the majority of my client side code using AngularJS. However, I find that when using Twitter Bootstrap, it requires a lot of HTML code to create forms. While solutions like simple-form exist, they require creating a model instanc ...

The meaning gets blurred when using 'this' in a prototype method

Alright, so I am working on a node application that utilizes express. In this particular application, there's an express route set up like this: var MyObject = require('./myObject') , myObject = new MyObject(); app.post('/api/w ...

Update information without the need for an xhr request in the back-end using jQuery

To keep notification updated with any changes in the database without causing a slowdown to the website, I implemented the following solution: HTML Code: <div id="myid">{{ $db_data }}</div> Back-end Request (utilizing Laravel): $db_data = A ...

Eliminate nested object properties using an attribute in JavaScript

I am working with a nested object structured like this const data = [ { id: '1', description: 'desc 1', data : [ { id: '5', description: 'desc', number :1 }, { id: '4', description: 'descip& ...

Tips on creating a one-of-a-kind AWS S3 file name

When it comes to sending my file to an s3 bucket via the front end, I've decided that this method seems more efficient based on what I've researched. However, I have encountered a challenge with some of my schemas and collections. Since they are ...