1

I get undefined whenever I get the value of a property of an object.

function run(id){
   var report = services.getReportInfo(id);

   var childReport = {
       id: newGuid(),
       parentId: report.id, // i get undefined
       reportPath: report.path  // i get undefined
   };

   ...
}

services.js

angular.module('project.services').factory('services', function(){

   var reports = [
      {
         ....
      },
      {
         ....
      }
   ];

   function getReportInfo(id){
      var report = reports.filter(function(element){
          return element.id === id;
      });
   };

   return{
      getReportInfo: getReportInfo
   };
}

Whenever I put breakpoint on my var report = services.getReportInfo(id) it could contains the correct values for each property of the my report object. However, when I get the report.id or report.path, I get undefined value.

--Edited--

Oh, I know now where I got wrong.

The getReportInfo function returns an array and I'm accessing the properties without telling from what index should it get the values for the said properties.

function run(id){
    var report = services.getReportInfo(id);

    var childReport = {
       id: newGuid(),
       parentId: report[0].id,
       reportPath: report[0].path 
    };

    ...
}

I placed static index 0, since I know that the array will always have a length of 1.

chary
  • 57
  • 13
  • Where do you inject the service inside the run function? Is the run function inside of a controller? – Sanjo Oct 07 '13 at 02:30
  • Yes Sanjo, the run function is inside a controller. I just didn't include it to lessen the code written above – chary Oct 07 '13 at 03:52

2 Answers2

2

You are not returning anything from the .factory method and the getReportInfo is also not returning anything. For what you are trying to do, try to use .service method:

angular.module('project.services').service('services', function(){

   var reports = [
      {
         ....
      },
      {
         ....
      }
   ];

   this.getReportInfo = function (id){
      var report = reports.filter(function(element){
          return element.id === id;
      });
      return report;
   }
}

Here is a good explanation on how to use .factory and .service:
Confused about Service vs Factory

Community
  • 1
  • 1
marcoseu
  • 3,892
  • 2
  • 16
  • 35
0

Two immediate issues with the code I can see:

1) Your factory function needs to return a value or constructor function. Right now your code is not initializing the factory to any value.

2) Your getReportInfo function also doesn't return a value, yet you are assigning the function result to a variable.

Read more here: http://docs.angularjs.org/guide/dev_guide.services.creating_services

Adam
  • 1,143
  • 7
  • 7
  • Hi Adam, thank you for your answer :) as for #2, it does return a value. When I put a breakpoint and check the report variable, I see the values I needed. – chary Oct 07 '13 at 03:55