Using AngularJS to send the $http response back to the calling object

Is there a way to pass the response value to the parent object, specifically the invoker of an http service call in AngularJS? I have a BaseModel that performs the GET request as shown below. The goal is for the basemodel object instance to hold the response values. I am trying to achieve this without using broadcast and on methods.

To invoke the object:

 model = new BaseModel();
 model.get();

Definition:

BaseModel.$service = ['$http', '$q',
   function ($http, $q) {
       return function () {
           return new BaseModel($http, $q);
       };

}];

The actual BaseModel:

function BaseModel($http, $q) {
   var q = $q.defer();
   this.http = $http;
   this.response = null; // this is to hold the response value
   this.get = function () {
       var request = this.http({
           url: 'http://blahblah.com?a=1&b=2',
           method: "GET",
       });
       request.success(function (response) {
           q.resolve(response);
       });
       
       q.promise.then(
           function(response){
               console.log(response, ' got response');
               //the idea is to have this.response = response
               return response;
           }
       );
       return q.promise;
   };

Answer №1

To access the instance variables of the BaseModel, make sure to use a self variable:

function BaseModel($http, $q) {
  var self = this;
  self.response = null;
  /* ... rest of the code ... */

    q.promise.then(function (response) {
      console.log(response, ' received response');
      self.response = response;
    });

  /* ... rest of the code ... */
}

This issue is not specific to AngularJS but rather a fundamental concept in JavaScript regarding object manipulation and the need to use a separate self reference to avoid conflicts with the this keyword within nested functions.

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

Guide to implementing a Bootstrap dropdown in an Angular application

I am implementing a bootstrap dropdown with checkboxes and looking to integrate it into Angular. http://codepen.io/bseth99/pen/fboKH (I have made modifications like wrapping the dropdown in a form) <form> <div class="container" ng-controller ...

Valums file-uploader: Restricting file uploads based on user's credit score

Currently utilizing the amazing file uploader by Valums, which can be found at https://github.com/valums/file-uploader One feature I am looking to incorporate is a limit based on the user's account balance. The initial image upload is free, so users ...

The ng-change function in Angular JS is triggered upon loading

I am facing an issue with a Select box where a function is being called on ng-change during page load. I want to prevent this function from running automatically on page load as it is not the intended behavior of ng-change. <select class="form-control" ...

Is it necessary to store tokens in cookies, local storage, or sessions?

I am currently utilizing React SPA, Express, Express-session, Passport, and JWT. I find myself puzzled by the various client-side storage options available for storing tokens: Cookies, Session, and JWT/Passport. Is it necessary to store tokens in cookies, ...

What is the most efficient way to dynamically alter the position of a div element within an HTML document using

In a scenario where a parent div contains multiple child divs, it is required that one particular child div named .div_object_last always stays at the end. Below is an example setup : HTML <div class="div_parent"> <div class="div_object"> ...

Error in Angular 1.6 caused by binding issues

Just started using Angular and encountering this issue. Error: Uncaught TypeError: Cannot use 'in' operator to search for '$ctrl' in subpackage I have a parent component and a child component where I have defined a function in the par ...

Determine the total number of arrays present in the JSON data

I'm currently working on a straightforward AngularJS project, and here's the code I have so far: This is my view: <tr ng-repeat="metering in meterings"> <td>1</td> <td>{{metering.d.SerialNumber}}</td> ...

Fluctuating and locked header problem occurring in material table (using react window + react window infinite loader)

After implementing an Infinite scrolling table using react-window and material UI, I have encountered some issues that need to be addressed: The header does not stick to the top despite having the appropriate styles applied (stickyHeader prop). The header ...

Best Practices for Iterating over Nested Objects and Arrays Using ng-repeat

I've been trying to use Angular's ng-repeat, but nothing seems to work for me. I'm attempting to loop through companies.users and display all the first names. Any assistance would be greatly appreciated! Thank you! <div ng-app="app" ng-c ...

Customizing error messages in Joi validationorHow to show custom

Hi there, currently I am utilizing "@hapi/joi": "^15.1.1". Unfortunately, at this moment I am unable to upgrade to the most recent Joi version. This represents my validation schema const schema = { name: Joi.string() .all ...

What steps can be taken to fix the recurring node error "EADDRINUSE"?

Having trouble running an http server through node as I keep encountering the EADDRINUSE error specifically on port 5000. I've attempted using sudo lsof -i tcp:5000 and sudo kill -9 [PID]. Here's a snippet of the shell command: Borealis:BackEnd g ...

403 Error Code - Access Denied when trying to access Cowin Setu APIs

While attempting to create a covid vaccine alert using the Cowin Setu API (India) in nodejs, I encountered a strange issue. Every time I send a get request, I receive a 403 response code from cloudfront stating 'Request Blocked', although it work ...

The event listener for changing radio buttons

Imagine we have two radio buttons <input type="radio" value="val1" name="radio1" onChange="change()"/> <input type="radio" value="val2" name="radio1" onChange="change()&quo ...

Converting a JavaScript animation into a video through server-side processing: A step-by-step guide

Attempting to tackle a challenging task but willing to give it a shot: Our team is currently working on developing a website that enables users to generate animations using javascript and html. However, our latest client request involves uploading the cre ...

receiving a null value from a dropdown selection in react native

As a beginner in learning react native, I am eager to retrieve the selected value from a dropdown in react-native. This is my constructor constructor(props){ super(props); this.state = ({ PickerSelectedVal : '' ...

Updating the status of a checkbox array within the reducer to reflect changes made in the user interface

I've implemented something similar in React: const CheckboxItems = (t) => [ { checked: true, value: 'itemsCancelled', id: 'checkBoxItemsCancelled', labelText: t('cancellations.checkBoxItemsCancelled&apos ...

Countdown timer that counts down in reverse when the browser is minimized

I am currently working on a JavaScript project where I have implemented a countdown timer in seconds. Once the timer hits zero, it triggers a specific function. The timer functions correctly, however, if the browser enters sleep mode or is minimized, the ...

What is the best way for Laravel to utilize the information provided via an Angular Ajax post request

Hi there, I'm currently working on my Angular app and I am attempting to send some data over to Laravel. $scope.add = function(){ if($scope.new_brand.trim() !=='') $scope.brands.push({name:$scope.new_brand}); $http.post('brand ...

"Reinvigorating Listboxes in AngularJs for Enhanced User Experience

I currently have two multiple listboxes set up as follows: When I select multiple values from the left listbox and click the right arrow, those values will be moved to the right listbox and removed from the left listbox. HTML <select multiple ng- ...

Multiple CSS styles are being employed simultaneously to render the webpage

Currently, I am utilizing JavaScript to choose different CSS styles for various accessibility options such as black on white text and larger text. The issue I am facing arises when switching the CSS sheet, as elements from previously selected sheets are st ...