Search code examples
angularjstoastr

use angular-ui-notification with Restangular Interceptor


I want to show a few notifications when the API returns certain codes in the response.. after some research I chose this module but I would like to be able to use these in a responseInterceptor in Restangular. Here is my current interceptor..

RestangularProvider.setErrorInterceptor(function (response) {
    if (response.status !== 0) {
      return debouncedReportError(response);
    }
  });
  toastr.options = {
    'closeButton': true,
    'debug': true,
    'positionClass': 'toast-top-full-width',
    'onclick': null,
    'showDuration': '200',
    'hideDuration': '300',
    'timeOut': '200000',
    'extendedTimeOut': '1000',
    'showEasing': 'swing',
    'hideEasing': 'linear',
    'showMethod': 'fadeIn',
    'hideMethod': 'fadeOut'
  };

  reportError = function (response) {
    var errorOutput;

    if (response.status==403 && response.data.error.code>20000){
      Notification.success('Success notification');
      debugger;
    }
    if (typeof response.data === 'string') {
      return toastr.error('An Error occured: ' + response.statusText, 'Error: ' + response.status);
    } else if (response.data.error_message != null) {
      return toastr.error('' + response.data.error_message, 'Error: ' + response.status);
    } else if (response.data.error && response.data.error.errors != null && !_(response.data.error.errors).isEmpty()) {
      errorOutput = _(response.data.error.errors).reduce(function (memo, value, index) {
        return memo + value;
      }, '');
      return toastr.error('' + errorOutput, 'Error: ' + response.status);
    } else if (response.data.error && response.data.error.message != null) {
      return toastr.error('' + response.data.error.message, 'Error: ' + response.status);
    } else {
      return toastr.error('An error occured on the back end.', 'Error ' + response.status);
    }
  };
  return debouncedReportError = _.debounce(reportError, 2000, true);
}

I am unable to insert the required service 'Notification'.. any help is much appreciated. Thanks guys.


Solution

  • as per this link, you can configure restangular in run method as well, so then you can configure it like below

    angular.module('myApp')
      .run(function(Restangular, Notification) {
        Restangular.setErrorInterceptor(
          function(response) {        
            Notification.Show()
           }
            return elem;
        });
      });
    

    though example shows you request-interceptor, you can configure any interceptor in this way...