0

i have a controller that calls a function in a service. this, in turn, calls a promise function inside the same service.

the problem is that i can't get the returned value in my controller.

the controller:

    function mainFunctionInControlelr() {       
       some code here...
       vm.evtHTTPFactory.getData() // calling the service
        .then(function(response) {
            console.log("the returned value is " + response.myReturned );
        });

               }

the service:

    factory.getData = function(parm) { 
        return factory.getABC(parm); // calling another method in the same service
    };      



    factory.getABC = function(parm) { 
        return $q(function(resolve, reject) {
            $http.get(PltConfig.APIPath + '/v1/............', {
                params: { inputParm: parm }
            })
            .success(function (response) {
                resolve(response.data.myReturned);
                return;
                } ) 
            });
        };

the issue is that getData, inside the service, is calling getABC, also inside the service. something is lost in the process. I need to have "myReturned" in the controller.

what do i need to put in getData (in the service) to make things work?

thanks a lot.

The Head Rush
  • 3,157
  • 2
  • 25
  • 45
user2568276
  • 89
  • 2
  • 13
  • 1
    In order to call `.then` on the promise (from within the controller), the service function has to return the _promise_ itself. Looks like your service code is a little off -- update it to return the promise itself, rather than the response in `.success`. https://docs.angularjs.org/api/ng/service/$q#$q-returns – Nathan Beck Jan 29 '19 at 15:19
  • Avoid the [`Promise` constructor antipattern](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it)! – Bergi Jan 29 '19 at 15:26

1 Answers1

0

I would use async await... like this:

in your function getData:

factory.getData = async function(parm) { 
    var data = await factory.getABC(parm);
    return data;
};

in your function controller:

async vm.evtHTTPFactory.getData() {
  var myResp = await vm.evtHTTPFactory.getData()
  console.log(myResp)}

An example here: https://jsfiddle.net/hernangiraldo89/frv4L2jh/4/

I hope it helps you!

Hernán Giraldo
  • 136
  • 1
  • 8