0

While calling a service, it calls API using $http method. In the same service I want to add conditional statement which is responsible to return another success or failure object without calling any API/URL. Something like this:

call someMethod()

{

if (statement true) { return httpResponseObject; }

else { return responseObject; }

}

The else part I need to return object responseObject in such a way so it can invoke the error block of method which is calling someMethod() as a service.

I tried return false;, return -1;, its not working. Also, I tried using ResponseText of XMLHttpRequest but didn't work.

Any help, how to create a HTTPResponse object which can be used in same way just as it would be returned by $Http response object. Something like attached snapshot:

enter image description here

5
  • you'll need to show more (actual) code than that, as your description of the problem is not clear Commented Jan 16, 2018 at 22:56
  • @JaromandaX : I need to create a response object just as it returned by $http response but without calling any API/URL, programatically. Commented Jan 16, 2018 at 23:08
  • sounds overly complicated, but as you haven't shown how this function wil be used, then it's still unclear Commented Jan 16, 2018 at 23:09
  • 1
    If you want to fake $http response, you need to return Promise same as $http does. This promise can be either resolved or rejected. Commented Jan 16, 2018 at 23:34
  • 1
    Use $q.resolve to return a successful promise. Use $q.reject to return a promise that is resolved as rejected. For more information, see AngularJS $q Service API Reference Commented Jan 17, 2018 at 1:06

2 Answers 2

0

Why not use a simple promise and call two functions success, error callback something like

someMethod().then(function(){
   //success logic
}, function(error){
   //error logic
})

You can fake a promise just like mentioned in comments and then use the above logic.

Sign up to request clarification or add additional context in comments.

Comments

0

As suggested by @bigless I solved by using Promise

return (Promise.reject("Error"));

It returns same object as it would have been returned by $http call.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.