code.cycling
code.cycling

Reputation: 1274

Getting undefined data when i called a service

So I have a question that i've been trying to solve for hours.

My problem is that I'm getting the data faster than my services to load.

gen-service

function genEmpId() {
settingsService.getSettings().then(function (data) {
    var comId = data.data[0].companyId;
    console.log(comId);
    var test = comId + ' - ';
    return test;
});}

controller

function genId() {
   var data = genService.genEmpId();
   console.log(data); // getting the data too fast how to put a callback ?
}

So when my controller load its calling the service but im getting an undefined return value.

Upvotes: 0

Views: 53

Answers (1)

Rahul Sharma
Rahul Sharma

Reputation: 10071

try this, In your code you not returning anything and another thing is it's async call to you have to wait until it finishes.

// gen-service

function genEmpId() {
  return settingsService.getSettings().then(function (data) {
    var comId = data.data[0].companyId;
    console.log(comId);
    var test = comId + ' - ';
    return test;
  });
}

// controller

function genId() {
  var data = genService.genEmpId().then(function (data) {
    console.log(data);
  })
}

Upvotes: 1

Related Questions