Error message stating: "Unable to read property 'then' as it is undefined within Angular nested promises."

I'm having trouble passing data back from a service to a controller in my AngularJS application. The service I am calling inside a factory makes an HTTP request for JSON data and then needs to modify it before returning it to the controller. However, I keep getting an error that says 'Cannot read property 'then' of undefined' when trying to use the then() method inside the $scope.getModifiedData function in my controller.

I have been reviewing the documentation on $q at https://docs.angularjs.org/api/ng/service/$q

Here is a snippet of my controller code:

$scope.getModifiedData = function() {
  var promise = employeesFactory.modifyData();
  promise.then(function(modifiedData) {
    console.log(modifiedData, 'modifiedData');
  });
};
$scope.getModifiedData();

And here is a snippet of my factory code:

var targetEmployeesAPI = 'http://sample.dev/api/employees.jsonp?callback=JSON_CALLBACK';

service.employeesRawData = function() {
  var deferred = $q.defer();
  $http({
    method: 'JSONP',
    url: targetEmployeesAPI
  }).success(function(data) {
    employeesRaw = data.employees;

    deferred.resolve(employeesRaw);
  }).error(function() {
    deferred.reject();
  });
  return deferred.promise;
};

service.modifyData = function() {
  var deferred = $q.defer();

  service.employeesRawData()
    .then(function(employeesRaw) {

      // Modify data here

      modifiedData = {};

      if (modifiedData !== undefined) {
        deferred.resolve(modifiedData);
      } else {
        deferred.reject('Rejected');
      }

    return deferred.promise;
  });
};

Answer №1

Simply change it.

service.updateData = function() {
  var deferred = $q.defer();

  service.staffRawInfo()
    .then(function(employeesRaw) {

    ...

    return deferred.promise;
  });
};

on

service.updateData = function() {
  var deferred = $q.defer();

  service.staffRawInfo()
    .then(function(employeesRaw) {

      ...
  });

  return deferred.promise;
};

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

Creating a custom Angular filter that leverages the power of $http - a

I want to make a retrieval request using $http in AngularJS and then display the obtained result on the front-end. To achieve this, I'm using {{ URL-STRING | iframely }}. 'use strict' angular.module( 'iframely', [] ).filter( &ap ...

protractor: verifying the focus of a particular input field

Is there a way to check if an input field is currently in focus using protractor? I am attempting the following: it('should focus email field', function(){ expect(element(by.model('login.email')).getAttribute('id')).toEqu ...

How to automatically adjust select view in AngularJS as model value is updated

My select element is structured as follows: <select data-ng-model="transaction.category" class="form-control" data-ng-options="category.name group by category.parent for category in categories" required> </ ...

Bearer Token CORS preflight request in Web Api 2

I have developed a web application with an AngularJS front-end and a Web Api 2 backend, utilizing bearer tokens for authentication. Everything functions correctly in FireFox and IE, but occasionally in Chrome, the initial login request is pre-flighted. B ...

Designing motion graphics for a browser game

As I delve into learning about Node.js, Angular.js, Socket.io, and Express.js, my current project involves creating a multiplayer poker game like Texas Hold 'Em. However, despite spending a considerable amount of time browsing the internet, I have bee ...

Does the `transitions.onStart` function in Angular 1.6 get called before or after the window load event?

Is there a way to ensure that my function is called before the window load event fires? I need a different transition method to achieve this. ...

AngularJS object array function parameter is not defined

Recently, I've been honing my AngularJS1x skills by following tutorials on Lynda and Udemy. One tutorial involved creating a multiple choice quiz. To test my understanding, I decided to modify the code and transform it into a fill-in-the-blank quiz. ...

Secure your browsing experience with AngularJS authentication prompt

Currently, I am working on building an application using AngularJS for the front-end and JavaEE for the back-end. In my AngularJS application, I am trying to access a REST resource provided by the back-end which is protected with JAAS authentication, allow ...

Debugging and ensuring the functionality of Cordova (Phonegap) HTTPS connections

There is an HTTPS site with an API that needs to be accessed. I need to work from Cordova (AngularJS) with its HTTPS API. Additionally, I want to debug the AngularJS app in a web browser (Chrome) because it's much quicker compared to rebuilding and ...

In the 4.13.1 version of Express, req.body is not defined

I'm facing a problem and seeking help to find the solution. Here's what I have in the Angular view: <form ng-submit="submit()"> <input ng-model="stickie_text" type="text" id="sticky_content" /> <button type="submit" id="add_stick ...

How can I retrieve a specific key from a nested array while using ng-repeat to iterate through it

I have successfully created a code snippet that retrieves JSON data and displays it in HTML using AngularJS. <div class="activity" ng-app="stream" ng-controller="streamCtrl"> <ul ng-repeat="x in myData"> <p class="au ...

Angular Material - Header Selection Bug

Trying to implement a Select Header is giving me the error message "Error: md-input-container can only have one child input, textarea or select element!" This is the code causing the issue: <md-input-container> <label>Vegetables</l ...

Experiencing an issue with Protractor e2e testing: "Encountered a Jasmine Spec timeout: WebDriver Control Flow Reset"

Seeking assistance with an ongoing challenge that has me stumped after days of searching I'm in the process of using Protractor for end-to-end testing of an AngularJS application While I have Protractor set up and running a test, whenever I try to r ...

AngularJS Incorrectly marked checkbox

I am encountering an issue with a template using AngularJS. The template displays a list of books with checkboxes for performing batch actions such as deleting the books. If the list gets too long, the books are paginated. The problem arises when I check ...

Retrieve ng-model information beyond the scope of the controller

Below is the code I have written: <span ng-controller="calanderCtrl"> <input type="text" ng-model="onDate"> </span> <pre>user.name = <span ng-bind="onDate"></span></pre> I understand that it is outside of the n ...

Attempting to grasp the fundamentals of angular Routing, however, upon attempting to reload the page, nothing appears to be displayed

While working in the Bracket editor, I created a file structure with various files located under the 'scripts' tags within the Index.html file. The root folder is named 'projectAngular', inside which there are subfolders like 'appC ...

The AngularJs 2 framework encountered an issue with booting up after attempting to combine all TypeScript files into a single JavaScript file

I am currently utilizing Angular 2 with TypeScript (V-1.8) in my project setup. I have configured my tsconfig to output the code into a single .js file. This single.js file includes the necessary code to bootstrap the application, as the boot.ts file is al ...

How can I dive into a nested array to access the properties of an object within?

My array, called sportPromise, is structured like this: 0: Array[0] 1: Array[1] 2: Array[2] 3: Array[3] When I run console.log(angular.toJson($scope.sportPromise, 'pretty'));, the output looks like this: [ [], [ { "id": 5932, ...

"Exploring the Power of ZF2 with Restful APIs and Image

I am currently in the process of developing a website utilizing Zend Framework 2 in combination with AngularJS. The backend consists of a restful webservice running on ZF2, while AngularJS is used on the client side to interact with this webservice. My ne ...

Adjusting editable property in FullCalendar during script execution

Currently, I am working with Angular JS and fullCalendar to customize the functionality of my calendar. My goal is to change the editable property of the calendar when a button is clicked. Although it seems like a straightforward task, I am facing difficul ...