Intercepting in AngularJS: Leveraging parent controller's methods

Within my application, I am performing various manipulations with HTTP requests. For example:

      $scope.fetchData = function(id) {
        $http.get('/app/' + id, {
            headers: {
              'Content-Type': 'application/json',
            }
          })
          .success(function(response) {

          })
          .error(function(data, status, headers, config) {
          });
      };

      $scope.showNotification = function (message) {
        var modalHtml = '<div class="modal-header"><h3>Notification</h3></div>';
        modalHtml += '<div class="modal-body"><strong>' + message + '</strong></div>';
        modalHtml += '<div class="modal-footer"><button class="btn-md btn-green pull-right" ng-click="$dismiss()">OK</button></div>';
        $scope.modalInstance = $modal.open({
          template: modalHtml,
          size: 'sm',
          backdrop: 'static',
          keyboard: false
        });
        $timeout(function () {
          $scope.modalInstance.close('closing');
        }, 5000);
      };

In addition, I have created an interceptor as follows:

var handleError = function (rejection) {
        var rootScope = rootScope || $injector.get('$rootScope');
        console.log(rootScope.showNotification('123'));        
        ***
        return $q.reject(rejection);
    };

However, in this interceptor, how can I call the $scope.showNotification() method when there is an error?

I could handle it like this:

$scope.fetchData = function(id) {
            $http.get('/app/' + id, {
                headers: {
                  'Content-Type': 'application/json',
                }
              })
              .success(function(response) {

              })
              .error(function(data, status, headers, config) {                
                $scope.showNotification('An error occurred.');
              });
          };

But this approach may not be ideal. What other options do I have?

Answer №1

Utilize the $rootScope in conjunction with $broadcast and $on as a way to create an event bus for communication between components. It's important to note that using these methods may impact performance, so it's crucial to be cautious when implementing them.

In your service:

var responseError = function (rejection) {
    var rootScope = rootScope || $injector.get('$rootScope');
    ....
    $rootScope.$broadcast('responseError',{
        message: 'Rejection Reason' }); 

And in the controller:

$scope.$on('responseError', function(event, data){
    $scope.displayAlert(data.message); });

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

Once the form is submitted, Vue automatically resets all the data

export default { data() { return { usrName: null, pass1: null, pass2: null, regState: {stateCode:-1}, } }, methods: { register: function () { this.axios.post("/login/", { baseURL: 'http://127 ...

What is the best way to invoke a function only once in typescript?

Struggling to implement TypeScript in React Native for fetching an API on screen load? I've been facing a tough time with it, especially when trying to call the function only once without using timeouts. Here's my current approach, but it's ...

Even after trying to hide the legend in a Radar Chart using the configuration option `legend: {display: false}` in chart.js, the legend

Having trouble removing legend from Radar Chart in chart.js even when using legend: {display : false}. The code is being utilized and then displayed with HTML/JS. Here is the provided code snippet: var options5 = { type: 'radar', data: { ...

Mapping objects in an array with Javascript

This code snippet is intended for a React Native Chat app. The structure of my data should look something like this: const chatData = [ { id: 1, name: 'John Doe', messages: [ {text: 'Hello', sentAt: 'time here' ...

The result from the AngularJs promise is coming back as undefined

I am facing an issue while trying to implement the login function of my AuthService factory in conjunction with my AuthLoginController controller. The problem arises when the User.login function is triggered with incorrect email and password details, causi ...

An unexpected error event occurred while using gulp uglify

My current approach involves using gulp-uglify and gulp-concat to minify and concatenate my JavaScript files. The specific code for this process is outlined below: gulp.task('scripts', function() { gulp.src([ './development/ ...

Creating a Google map with multiple markers within a 10 km radius of the current location in a rectangular shape

Currently, I am working on a web application that utilizes Google Maps and AngularJS. One of the requirements is to display multiple markers on the map, but only those within a 10km range from the corners, not in a circular radius. In order to achieve th ...

Transferring scope between pages without the need for an angular service definition

Looking to open a new JSP page while passing the $scope in order to utilize an array response generated in the initial page. Example from test.js file: (function() { 'use strict'; angular .module('test', []) .control ...

Tips for making an input field that overlays text

I am currently working on a project that involves creating multiple cards using Bootstrap. Each card consists of a header, body, and footer. When a card is clicked on, I want an input field to appear in the header, footer, and body sections, overlaying the ...

How can the printing of content be adjusted when the browser zoom function is activated?

Is there a way to prevent the content from zooming when printing while the browser is zoomed in? The goal is for the printing (using iframe) to remain unchanged even if the browser is zoomed. I attempted: document.body.style.transformOrigin = 'top le ...

When attempting to reload a single page application that utilizes AJAX, a 404 error is encountered

Recently, I've been working on coding my personal website and have successfully created a single page application using ajax. The content is dynamically loaded between the header and footer whenever a navigation bar link is clicked. To enable the back ...

My discord.js bot remains silent in response to a user's message, even when no errors are present

My Discord bot is using version 13.1.0 of discord.js and my Node version is 16.7.0. I utilized the commands npm init to generate a package.json file and npm install discord.js to install the Discord package. The code for the bot is written in index.js, an ...

Using regular expressions to modify parameter values in a command-line argument between nodes and npm scripts

While experimenting with node.js, I encountered a perplexing behavior related to command line arguments: I have a program that utilizes a regex pattern to identify test files. This regex is passed as a command line argument: node index.js --require src/** ...

What could be causing ng-click to not trigger my controller function?

One of my services is dedicated to fetching an access token from the REST API. Here's the snippet of code for it: var myServices = angular.module('myServices ', ['ngResource']); myServices .factory('Auth', ['$resou ...

Tips for retrieving the ID value of the <li> element using JavaScript and AJAX

Here is a snippet of code I've been using to send the value of an <option>: function getXhr() { var xhr = null; if(window.XMLHttpRequest) // Firefox et autres xhr = new XMLHttpRequest(); else if(window.ActiveXObject){ // I ...

How can I send identical posts to multiple servers and link specific data to each post?

I am attempting to send a post request to multiple servers using jQuery, potentially facing issues with CORS. I have an array containing the jQuery posts and I register the same callback function for each individual one like this: var requestUrls = getReq ...

How can I quickly duplicate the design of a JSON Object?

Perhaps the title is a bit basic. Essentially, I am looking for something similar to mysqldump ... --no-data .... For instance, I have a JSON object structured like this: { "key1" : "value1", "key2" : "value2", "key3" : { "key3a" : 1, "key ...

Display iframe as the initial content upon loading

Seeking solutions for loading an iframe using jQuery or Ajax and outputting the content to the page once it has been loaded. The challenge lies in loading an external page that may be slow or fail to load altogether, leading to undesired blank spaces on th ...

Use PHP to transform an array into JSON format, then access and retrieve the JSON data using either jQuery or JavaScript

I have successfully generated JSON data using PHP: $arr = []; foreach($userinfo as $record) { $arr[] = array( 'BAid' => $record->getBAid(), 'BCid' => $record->getBCid(), 'BA ...

What is the best way to toggle the visibility of a side navigation panel using AngularJS?

For my project, I utilized ng-include to insert HTML content. Within the included HTML, there is a side navigation panel that I only want to display in one specific HTML file and not in another. How can I achieve this? This is what I included: <div ng ...