Slimshadddyyy
Slimshadddyyy

Reputation: 4073

AngularJS - Pass Error from Service to Controller

Service.js

    myService.serviceName = function (userId) {
            return $http({
                method: 'POST',
                url: '/someUrl'
            }).then(function successCallback(response) {
                return response.data;
            }, function errorCallback(response) {
                console.log('Service errorCallback');
                console.log(response);
            });
    };

Controller.js

myService.ControllerName(data.id)
        .then(function successCallback(data) {
            //do processing here
        }, function errorCallback(response) {
            toaster.pop({
                type: 'error',
                title: 'Display Error Message!'
            });
        });

In service, we are getting error status code in console viz -1, -2 and based on that code we are displaying custom error message to the user.

Upvotes: 1

Views: 1063

Answers (2)

EternalLight
EternalLight

Reputation: 1328

The first thing that comes to my mind is to accept callbacks from the Controller.

myService.serviceName = function (userId) {
    return $http({
        method: 'POST',
        url: '/someUrl'
    })
};

And in your Controller:

myService.serviceName(123).then(function(response) {
    // Do the processing.
}, function(error) {
    // Check the error and change the UI accordingly. 
});

If you need to make the processing within the service, you might want to use the $q service. In this case, you would need to inject it into your Service.

myService.serviceName = function (userId) {
    var defer = $q.defer();
    $http({
        method: 'POST',
        url: '/someUrl'
    }).then(function (response) {
        // Do the processing.
        defer.resolve(response);
    }).catch(function (error) {
        defer.reject(error);
    });
    return defer.promise;
};

In your controller:

myService.serviceName(123).then(function(response) {
    // Indicate that everything went OK.
}, function(error) {
    // Check the error and change the UI accordingly.
});

Upvotes: 1

Maarten Bicknese
Maarten Bicknese

Reputation: 1548

You could add functionality to add callbacks to the service.

This way the controller can register its own callback method to the service. Which in its turn will call said callback method when the error occurs. Notifying the controller of the occurred error and desired message.

Upvotes: 0

Related Questions