0

If I have a service that returns an $http promise, then how can I attach into the errorCallback?

MyService:

self.getData = () => {
    let promise = $http.get('/api/getData').then(x => {
        return x;
    }, x => {
        //This is reached on server-side error
        return x;
    });
    return promise;
};

Directive controller:

MyService.getData().then(x => {
    //This is always executed regardless of whateher the success or error functions are executed in the promise
}, x => {
    //This is not executed
});

The errorCallback is executed, but then when trying to attach to that promise in my directive, it always runs the success function.

tic
  • 2,484
  • 1
  • 21
  • 33
  • 1
    If you don't plan on doing anything with the value, don't pass a function at all. – Bergi Sep 27 '17 at 17:44
  • @Bergi This is an example, not complete code – tic Sep 27 '17 at 17:45
  • Then please post what your actual code is doing. In any case, when you `return` a result value from a rejection handler it means that you *handled* the rejection. To reject the resulting promise with a new value, `throw` it. – Bergi Sep 27 '17 at 17:47
  • It is doing the above. Normally I would post the smallest snippet of code to recreate my error on stackoverflow, rather than 6000 lines of code that aren't relevant. If my question is unclear, I am happy to update it to be better explained. – tic Sep 27 '17 at 17:51
  • You might want to [edit] it to `return doSomething(x)` so it's clear the callback is not just the identity function, which is what my first comment was addressing. (Apart from that the question is quite clear and should be solved by the duplicate) – Bergi Sep 27 '17 at 17:55
  • Hey @tic , maybe if you provide a jsbin or jsfiddle, that would help us help you. =) – jlr Sep 27 '17 at 17:55
  • 1
    This has been marked as duplicate so I can't share the answer that @Bergi provided, but instead of `return x` inside the `errorCallback` of the Service, doing `throw x`, it correctly runs the `errorCallback` in the directive's function. I believe the linked answer is not very clear and is only similar to this question, so this would be a useful additional question and answer. – tic Sep 27 '17 at 17:59
  • 1
    You have to re-throw the error not just return it. You can use AngularJS's $q service to do that. Use `return $q.reject(x);` in your error callback. I also tend to use `$http.then( x => {} ).catch( x => {} )` instead of both the success and error in the `.then` I find it easier to read that way – Jeff Adams Sep 27 '17 at 18:00
  • @JeffAdams It might be easier to read, but [it does not always do the same](https://stackoverflow.com/q/24662289/1048572). – Bergi Sep 27 '17 at 18:20

0 Answers0