The service's wrapping of the http.get() call resulted in an undefined return

I've run into an issue where the http request is successful in fetching data from the server, but for some reason, $scope.catalogue always ends up being undefined. It seems this could be happening because the assignment occurs before the response is returned from the server. I thought I had handled the asynchronous nature of the operation within the service?

angular.module('catalogue', [])
.factory('Catalogue', ['$http', function($http){
    return {
        getCatalogue: function(){
            $http.get('./server.php').then(function(response){
                return response
            });
        },
        setCatalogue: function(JSON){
            $http.post('./server.php', JSON).success(function(){return 'successfully set data'});
        }
    }
}])

So in my controller, here's what's implemented:

$scope.catalogue = Catalogue.getCatalogue();

Answer №1

Make sure to always fulfill the promise:

fetchItems: function(){
    return $http.get('./inventory.php')
}

Then in your script, you should do

Inventory.fetchItems().then(function(data){
    $scope.items = data;
});

Answer №2

If you want to enhance the separation of concerns, consider using Angular promises in a more efficient way. Here is an example:

angular.module('myapp',[])
  .service('Github', function($http, $q)
  {
    this.getRepositories = function()
      {
        var deferred = $q.defer();
        $http.get('https://api.github.com/users/defunkt')
        .success(function(response)
        {
          // Perform actions on the response
          response.username = response.login + ' ' + response.name;
          // Implement data filtering, manipulation, and decoration from the API
          // Then resolve the response
          deferred.resolve(response);
        }).error(function(response)
        {
          deferred.resolve(response);
        });
        return deferred.promise;
      }
  })
  .controller('MainCtrl', function($scope,Github) {
       Github.getRepositories().then(function(dt){
        $scope.user = dt;
       });
  });

To see a demonstration, check out the Plunker I created: http://plnkr.co/edit/r7Cj7H

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

Modify the ion-view view-title for each individual page

I have encountered an issue where the view-title does not update properly. Specifically, I change the view-title by assigning $scope.name = user.name and then using <ion-view view-title="{{name}}">. Although the change is visible on the same page, i ...

I want to show a string array in the ui-grid, with each ui-grid displaying a single row for each string in the array

I am trying to showcase each piece of data from an array in its own individual ui-grid row. Can someone please assist me in verifying if this approach is correct? For example, I want data[0] to be displayed in one ui-grid, and data[1] in another ui-grid, c ...

Looking for guidance on how to specify the angular direction in the ng-repeat

I am facing a challenge with the structure of my ng-repeat directive and I am having trouble navigating through it. Here is a representation of the data in array format JSON style {"data":[ ["sameer","1001", [ {"button_icon": ...

Is there a way to incorporate the use of quotation marks within the ng-bind directive in AngularJS?

Is there a way to insert phoneNo["phoneno"] into an HTML input using the ng-bind directive in Angular? While {{phoneNo["phoneno"]}} can display the data, it results in a syntax error when I try to put it like this: <input class="form-control" type="t ...

Exploring the Dynamic Styling Power of Angular's ng-class Directive Alongside the Transition from

I recently updated my app from Fontawesome version 4 to 5 by following the guidelines provided HERE. Everything looks great and appears to be working smoothly, except for the dynamic icons... In my Angular-based app, the icon to display is often dynamic: ...

What is the best way to manage photos from your phone without having to upload them online?

I'm currently developing an application using AngularJS/Javascript, HTML, and CSS within a cloud-based environment on c9.io. My next task is to create and test an app that can access the phone's photo album, apply filters to images, and I'm ...

What is the purpose of enclosing an Angular app within a function?

As I delve into learning Angular, I've encountered a recurring snippet in the app.js file across various resources: (function () { \\\myAngularModules })(); Despite its prevalence, the explanation provided is often just ...

What is the proper way to utilize a filtered object based on its properties within an Angular controller?

Currently, I am working on developing a stacked graph along with its associated table. To retrieve the necessary JSON data, I am utilizing $http.get() and then assigning it to $scope.dataset. Here's a snippet of the HTML: <input ng-model="_search ...

Oops! Looks like we encountered a fatal error while running the unit tests. Unfortunately, the unit

After setting up the project environment and successfully installing grunt, I attempted to run grunt in the terminal which resulted in the following output: https://i.stack.imgur.com/4xnll.png I proceeded to follow the steps. Running grunt build --env ...

What is the best way to use AngularJS to extract values from the first dropdown menu that are linked to the values selected in the second

How can I link values in two dropdowns using AngularJS? Hello everyone, I have set up two dropdown fields in MyPlunker and within the ng-option tag, I have applied a filter like filter:{roles: 'kp'} to only display users with the role of kp. T ...

Adjusting the scope value following the completion of an HTTP request in AngularJS

I have a controller where I am making an ajax call to fetch some data. After the successful callback, I assign values to $scope variable as shown below. $http.get(GlobalService.getDomainUrl() +'/hosts/attr').success(function(data){ //Afte ...

Tips for updating a column with just one button in AngularJS

On my list page, there is an Unapproved button. I am new to angular and struggling to figure out how to retrieve the post's id and update the corresponding column in the database to mark it as approved. Can someone provide guidance on how to accomplis ...

How to choose multiple checkboxes in AngularJS by utilizing the shift key and mouse click feature?

Is it feasible to utilize shift and mouse click for selecting multiple elements on a table using AngularJS? In my table, the first column consists of checkboxes and I am interested in employing the SHIFT key along with mouse clicks to select several rows ...

Is it possible to simultaneously use two $scoped variables within an Angular controller?

Currently, I am developing an angular application that connects to a Rails backend and interacts with the database through API calls to receive JSON objects. My challenge lies in defining multiple scoped variables within a controller. At the moment, I have ...

Understanding Restangular with Typescript can be challenging, especially when dealing with a 'restangularized' response object

In my project, I am working with Angular 1.5.x using TypeScript in combination with restangular to access a remote API. Here is an overview of the scenario: The API endpoint I am connecting to is http://localhost:53384/api/timezones. Making a GET request ...

Retrieve the value of $state from within the template

Explanation I have developed an application that features a left-hand menu with multiple menu items. Upon clicking on an item or accessing it via a URL, I aim to emphasize the selected item by applying the 'active' class to the corresponding < ...

Angular encountered an issue with an HTTP POST request, as the 'Access-Control-Allow-Origin' header was not found on the requested resource

I have been attempting to transmit data to a servlet using Angular HTTP POST requests. var httpPostData = function (postparameters, postData){ var headers = { 'Access-Control-Allow-Origin' : '*', &a ...

Validating Angular UI without requiring an input field (validating an expression)

Currently, I am utilizing ui-validate utilities available at https://github.com/angular-ui/ui-validate The issue I am facing involves validating an expression on a form without an input field. To illustrate, consider the following object: $scope.item = ...

Issues with link behavior when using Angular UI-Router

I am just starting to learn AngularJS and I'm trying to figure out how to pass a parameter using anchor tags within the $stateProvider code. I've been attempting to do so, but it doesn't seem to be working. Can someone guide me on the correc ...

Customize the HTML tags in the Froala text editor with easy insertion and removal

In my AngularJS project, I am utilizing Froala editor. I want to create a unique functionality where a custom button wraps selected text with <close></close> tags when activated. Moreover, if the selected text is already wrapped with these tags ...