AngularJS HTTP call response

Below is a snippet of my code:

var object = null
app.controller("controller",function($scope,service){
    $scope.search=function(){
        service.findData().then(
            function successCallback(response){
                object = response.data
            },
            function errorCallback(response){
                alert("error")
            }
        )
        console.log(object)
    }
})

Despite my efforts, when I print the object it remains null. So my question is: how can I access response.data outside of the function?

Your assistance is greatly appreciated!

Answer №1

Back in the days of AngularJS, it was common practice to assign the controller to a variable.

app.controller("controller",function($scope,service){
    var self = this;
    $scope.search=function(){
        service.findData().then(
            function successCallback(response){
                self.handleResponse (response.data)

            },
            function errorCallback(response){
                alert("error")
            }
        )
        console.log(object)
    }

    self.handleResponse = function(data){

    console.log(data);
    // data here will be the response.data from the service
    // You can write your logic 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

What is the best way to display two columns in each row using Angular?

Can you please provide guidance on how to display two columns in each row using Angular? I am attempting to showcase only two columns per row, and if there are more than four items, I want to display them on an ion-slide. Further details will be provided. ...

The controller in AngularJS fails to function properly after the initial page refresh

I am currently utilizing AngularJS in my hybrid Ionic application. Here is my controller: .controller('SubmitCtrl', function($scope) { console.log("It only works when the page is refreshed!"); }); The console.log function runs perfectly fine ...

Navigating a variety of page styles and views in Angular 1 using routing

Following a tutorial, I have set up code that routes to various pages related to the main type of document used in the application: angular.module('loc8rApp', ['ngRoute', 'ngSanitize', 'ui.bootstrap']); function ...

Retrieve data from a list using an API

I am currently working on creating a dynamic list by fetching data from an API. The goal is to display detailed information in a modal when a user clicks on a specific item in the list. While the list itself is functioning properly, I am encountering an i ...

AngularJS Default Option Selection

I am encountering some difficulties with the preselection of a select-input in angularJS. The select-box is being populated by an array. <select class="form-control" ng-model="userCtrl.selected_country" ng-options="country.name for country in userCt ...

ways to access a designated nodal point in angularJS from a constantly updating data source

I am in need of assistance with how to open a specific node using angularJS from a dynamic data source. I have been able to toggle (hide/show) the sub nodes, but what I would like is for clicking on a specific node to only show its sub-nodes. Currently, wh ...

Which one should you begin with: AngularJS or Angular 2?

Interested in learning Angular and curious about the differences between Angular, AngularJS, and Angular 2. Should I focus on educating myself on Angular or go straight to Angular 2, considering it's now in beta version? Is there a significant differ ...

Angular animations: triggered by user interaction

I'm encountering some difficulties with animating elements in my Angular application. The issue involves a grid made up of cells (created using ng-repeat). What I'm aiming to achieve is a simple animation: when a cell is clicked, it should disapp ...

Unregistering an event with AngularJS

Exploring the functions of a controller named MyCtrl: class MyCtrl { constructor($scope, $rootScope, ...) { this.$scope = $scope; this.$rootScope = $rootScope; this.doThis = _debounce(this.resize.bind(this), 300); ... ...

I am facing difficulties retrieving the JSON object returned from the Express GET route in Angular

After setting up an express route, the following JSON is returned: [{"_id":"573da7305af4c74002790733","postcode":"nr22ry","firstlineofaddress":"20 high house avenue","tenancynumber":"12454663","role":"operative","association":"company","hash":"b6ba35492f3 ...

Issue with Protractor locating element even though everything appears to be in order

I'm having trouble locating this element with Protractor. It's really frustrating me. I double-checked in the dev console and the element definitely exists. Any suggestions on why it's not being found? <download path="api/backup_jobs/e ...

Issue: 10 iterations of $digest() have been exceeded

I'm currently facing an issue with my code that involves repeating and displaying the items in a cart. <div ng-repeat="retailer in cart.getOrderedByRetailer()" > <ion-item> {{retailer.retailer_name}} </ion-item> ...

Optimal method for defining controllers in AngularJS

As a newcomer to AngularJS, I find myself faced with the dilemma of determining the best approach for creating a controller within the ng-app="mainApp". In traditional programming languages, it is common practice to keep related data together. However, in ...

Adding two headers to a post request in Angular 2 - a step-by-step guide!

Is there a way to combine 2 headers in the following code snippet: appendHeaders(json: PortfolioVO) { var newJson = JSON.stringify(json); var allHeaders = new Headers(); allHeaders.append('Content-type' , 'application/jso ...

Utilizing URL encoding instead of JSON when using Postman

I've hit a roadblock - I've spent almost the whole day trying to solve this issue. We are working on integrating csrf security into our website, which is built with play framework 2.5.9 and angularjs 1.x. I've added the csrf components and t ...

converting JSON to date format in angular

.controller('feedCtrl', ['$scope', '$http', function($scope, $http) { $http.get('items.json').then(function(response) { $scope.items = response.data; $scope.user = localStorage.getItem("glittrLoggedin"); ...

The preflight OPTIONS request for an AJAX GET from S3 using CORS fails with a 403 error

I have come across various discussions and issues related to this topic, but unfortunately, I have not been able to find a solution yet. I am attempting to use AJAX GET to retrieve a file from S3. My bucket is configured for CORS: <?xml version="1.0" e ...

What is the best way to connect the button value with my ng-model data?

I'm having trouble getting the button value to bind to my ng-model. Any suggestions on how I should approach this? Currently, I am utilizing the datepicker from https://github.com/rajeshwarpatlolla/ionic-datepicker <div class="col"> <labe ...

The issue of Angular UI Bootstrap buttons not updating persists even after the removal of an

My Radio-bottoms are powered by an Array for a Multi-Choice answer setup. <div ng-repeat="option in options"> <div> <button type="button" style="min-width: 100px" class="btn btn-default" ng-model="question.answer" btn-radio="' ...

An unresolved $httpBackend in Angular's unit testing environment without a defined response

I'm currently facing some difficulties with my first test, so I would appreciate your understanding. The purpose of this test is to evaluate a function that performs an HTTP post request: $scope.formData= 'client=' + $scope.client_selected ...