Angular.js controller unable to receive object array from $http.get in factory

I am fairly new to Angular development and I've hit a roadblock that's been holding me back for a while.

My factory is successfully creating an array filled with objects, specifically RSS feed data, and I can see it loading in the console. However, I'm struggling to get this array to return to the controller.

Any assistance you can provide would be greatly appreciated. Please excuse the messy code.

Main.js

function FeedCtrl($scope, GetFeed) {

    $scope.itemId = 0;
    //$scope.items = [];

    console.log('Get episodes in ctrl');
    $scope.items = function() {
        return GetFeed.getEpisodes();
    };
    console.log('display items from ctrl');
    console.log($scope.items());

  $scope.itemId = function(index) {
    $scope.itemId = index;
    console.log($scope.itemId);
    console.log($scope.itemNames[$scope.itemId].title);
  };

};

function EpisodeCrtl($scope, GetFeed) {
    //getFeed.pullFeed();
};

function GetFeed($http){

var episodeArray = [];

function items(){
   console.log('Firing pullFeed');
return $http.get('assets/feed.xml').then(function(response) {
    var x2js = new X2JS()
    var itemDef = x2js.xml_str2json(response.data);
    itemsObj = itemDef.rss.channel.item;

    var numOfItems = itemsObj.length;
    episodeArray.length = 0;
    for (var i = 0; i < numOfItems; i++) {
      episodeArray.push({
        title: itemsObj[i].title,
        link: itemsObj[i].link,
        author: itemsObj[i].author,
        pubDate: new Date(itemsObj[i].pubDate),
        summary: itemsObj[i].summary,
        duration: itemsObj[i].duration,
        description: itemsObj[i].description
      });
    }

    console.log(episodeArray);
    return episodeArray; 
  })
 };

 return {
    getEpisodes: function(){
      console.log(episodeArray);
      episodeArray.length = 0;
      items();
      console.log(episodeArray);
      return(episodeArray);
    }
 }
};

var app = angular.module('ctApp', ['ngMaterial', 'ngAnimate', 'ngRoute'])
.config(function($routeProvider) {
    $routeProvider
        .when('/', {
            templateUrl: 'list.html',
            controller: 'FeedCtrl'
        })
        .when('/about', {
            templateUrl: 'about.html',
           controller: 'EpisodeCrtl'
        });
})
.config( [ '$compileProvider', function( $compileProvider ) {
        var currentImgSrcSanitizationWhitelist = $compileProvider.imgSrcSanitizationWhitelist();
        var newImgSrcSanitizationWhiteList = currentImgSrcSanitizationWhitelist.toString().slice(0,-1)
        + '|chrome-extension:'
        +currentImgSrcSanitizationWhitelist.toString().slice(-1);
    }
])
.factory('GetFeed', GetFeed)
.controller('FeedCtrl', FeedCtrl)
.controller('EpisodeCrtl', EpisodeCrtl);

Answer №1

To grasp the concept of async calls and promises, you must understand how they function. Initially, you are on the right track - using `return` with an `$http.get` call returns the promise. Similarly, using `return` within the `.then` handler for `episodeArray` is correct.

However, in the subsequent function definition:

getEpisodes: function(){
      console.log(episodeArray);
      episodeArray.length = 0;
      items(); // this immediately returns without data
      console.log(episodeArray);
      return(episodeArray);
})

The call to `items` returns promptly, leaving `episodeArray` empty. Consequently, you end up returning an empty array object `[]`.

Therefore, you should `return items()` instead - as it will yield the same promise obtained from `$http.get().then()`.

getEpisodes: function(){
      return items();
})

Subsequently, you cannot simply assign the return value to `$scope.items` as in the current code, resulting in assigning the same empty array `[]`. Since a promise is returned, this is not what you require. Instead, you need to utilize `.then` in the controller to assign the value:

GetFeed.getEpisodes().then(function(episodeArray){
   $scope.items = episodeArray;
})

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

The parseFloat function only considers numbers before the decimal point and disregards

I need my function to properly format a number or string into a decimal number with X amount of digits after the decimal point. The issue I'm facing is that when I pass 3.0004 to my function, it returns 3. After reviewing the documentation, I realized ...

Display information from Node.js on an HTML page

I am working on a nodejs project where I need to login on one page and display the result on another page using expressjs. Below is my code for login.ejs: <!DOCTYPE html> <html lang="en" dir="ltr"> <body> <form method="PO ...

Can node JS code be written on the client side in Meteor 1.3?

Is it feasible to write Node.js code on the client side of Meteor 1.3? I tried looking for information but couldn't locate any evidence. Previous inquiries didn't mention its availability, however, I recall reading that it would be possible start ...

I'm looking to create a redirect feature using a QR code that will direct users to a specific page within my Flutter app. How

When the user scans the QR code, they will be taken to a secret internal page that can only be accessed through this specific link. I attempted to use various libraries such as , but it did not achieve the desired outcome. ...

Removing an element from an array by evaluating each item within the array

Input array: ["temp/1/Lounge/empty", "temp/1/Lounge/66,66,66,66,66,66,66,66,64,64,64,64…,64,64,64,64,64,64,64", "temp/2/Lounge/empty", "temp/3/Lounge/empty"] I have a list of elements like the above. Each element consists of four parts separated by s ...

Getting your JS project off the ground with NPM!

I am looking to develop a vanilla JavaScript project that utilizes npm packages, but I want to do it without using bundlers like Webpack. Here is a basic structure: index.html: <div id="app"></div> <script src="./index.js" type="module"&g ...

The significance of package-lock.json: Understanding demands vs dependencies

Within the dependency object of package-lock.json, there exist both requires and dependencies fields. For example: "requires": { "@angular-devkit/core": "0.8.5", "rxjs": "6.2.2", "tree-kill": "1.2.0", "webpack-sources": "1.3.0" }, "d ...

Steer clear of chaining multiple subscriptions in RXJS to improve code

I have some code that I am trying to optimize: someService.subscribeToChanges().subscribe(value => { const newValue = someArray.find(val => val.id === value.id) if (newValue) { if (value.status === 'someStatus') { ...

React Native - Listview triggering multiple refreshes when pulled down

As I attempt to implement the onScroll function for ListView to detect when a user has pulled the list down beyond a certain pixel value in order to trigger an AJAX call and refresh the list, I am facing an issue where it fires multiple times leading to a ...

When trying to retrieve an XML file that contains an escaped ampersand, a jQuery AJAX call is throwing an error

Before sending text input to a server to be stored in a MySQL database using XML, I first escape the "&" characters: var copyright = copyright.replace(/&/g,"&amp;"); The wrapped XML data block is then sent to the server through jQuery's ...

Unable to identify collision in JavaScript's 3D environment

I'm currently using three.js to develop a simulation of Brownian Motion, but I've hit a roadblock when it comes to getting the tiny molecules to collide with each other. This is the snippet I have at the moment: function intersects(sphere, other ...

Angular filter that replaces underscores with spaces

Looking for a solution to replace underscores with spaces in a string ...

The website displays perfectly in Atom, however, it is not functional in any web browser

My website is currently in the development phase, and I'm experiencing issues with certain div elements not positioning correctly once the site goes live. Specifically, the "Follow Us" tab at the bottom of the site, among other divs, has been affecte ...

The ng-controller directive is not functioning accurately

I attempted to execute the following basic HTML: <!DOCTYPE html> <html ng-app="tempApp"> <head> <script src="js_libs/angular/angular.min.js"></script> <script src="js_libs/angular/bootstrap.js"></script&g ...

tips on setting the time format in dimple.js

Trying to create a multi-line graph using dimple.js based on some sample code. I have flattened my JSON into an array and thought I had the code down, but I'm stuck. I am including these 2 libraries (using cloudflare dimple for security reasons): &l ...

A step-by-step guide on setting up flow types for @material-ui/core version 4

Is there a way to install flow types for material-ui/core version 4.x.x? It seems like the last update was for version 1.x.x here. The documentation on this topic is quite limited here. I'm unsure if there is still support for this, especially since t ...

Vuetify's paginated server-side datatable does not support client-side sorting

The Challenge The issue I am facing revolves around using a server-side paginated datatable. Specifically, when utilizing the Vuetify data tables component and attempting to perform client-side sorting due to using a public API that I did not develop, the ...

How can I rectify the varying vulnerabilities that arise from npm installation?

After running npm audit, I encountered an error related to Uncontrolled Resource Consumption in firebase. Is there a solution available? The issue can be fixed using `npm audit fix --force`. This will install <a href="/cdn-cgi/l/email-protection" clas ...

How can one properly extend the Object class in JavaScript?

I have a scenario where I want to enhance a record (plain Javascript object) of arrays with additional properties/methods, ideally by instantiating a new class: class Dataframe extends Object { _nrow: number; _ncol: number; _identity: number[]; co ...

AngularJs: uncomplicated rating system

Is there a way to increase a variable in an ng-repeat loop when clicked? <li class="item" ng-repeat="post in posts"> ... ... <button ng-click="incrementLike(post.like_count)">Like {{post.like_count}}</button> ... ... </li> $scope ...