1

每当我获得undefined对象属性的值时,我都会得到。

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

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

   ...
}

服务.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
   };
}

每当我在我的上放置断点时,var report = services.getReportInfo(id)它都可以包含我的报告对象的每个属性的正确值。但是,当我得到 report.id 或 report.path 时,我得到未定义的值。

--已编辑--

哦,我现在知道我错在哪里了。

getReportInfo 函数返回一个数组,我在访问属性时没有告诉它应该从哪个索引获取所述属性的值。

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

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

    ...
}

我放置了静态索引 0,因为我知道数组的长度总是 1。

4

2 回答 2

2

您没有从该.factory方法返回任何内容,并且 getReportInfo 也没有返回任何内容。对于您要执行的操作,请尝试使用.service方法:

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;
   }
}

这是关于如何使用.factory和的一个很好的解释.service
对服务与工厂感到困惑

于 2013-10-07T09:01:03.733 回答
0

我可以看到代码的两个直接问题:

1)您的工厂函数需要返回一个值或构造函数。现在您的代码没有将工厂初始化为任何值。

2)您的 getReportInfo 函数也不返回值,但您将函数结果分配给变量。

在这里阅读更多:http: //docs.angularjs.org/guide/dev_guide.services.creating_services

于 2013-10-07T02:31:29.437 回答