每当我获取对象属性的值时,我都会得到 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
};
...
}
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
};
}
每当我在我的 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。
最佳答案
.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
有一个很好的解释:
Confused about Service vs Factory
关于javascript - 无法在angularJs中获取我的对象的属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19216208/