我有angularjs项目,在主页上我想从我的mongodb数据库中显示几个选定的文章(对象)。在数据库中,我有两个集合 - 一个是包含几百个单独文章(对象)的“文章”,另一个是“主页”,其中我只有十个对象,只有'articleID'键,其中包含对象的ID第一次收集。我的问题是,当我硬编码控制器中的articleID所有工作正常,但是当我首先从'homepage'集合中获取articleID,然后将该值传递给从第一个集合中获取选定对象的函数'getArticle01'它不起作用。请,任何人都可以让我知道我做错了什么?如何在angularjs控制器中将参数值传递给服务函数?
这里是我的代码:
var articleId01 = '58da9967a8bccd763c48bdc0'; // if i hardcode article id here, all works fine
HomepageService
.findAllHomepages() // returns array with 10 objects from my api
.then(function(homepages) {
var articleId01 = homepages.data[0].articleID;
console.log(articleId01); // so far, all is ok, console logs value: '58da9967a8bccd763c48bdc0'
}, function(error) {
console.log('error', error);
})
.then(function(){
function getArticle01() {
HomepageService
.findHomepageById(articleId01) // unfortunately, value is not passed here
// .findHomepageById('58da9967a8bccd763c48bdc1') // if value is hardcoded, all is ok
.then(function(response) {
console.log(response.data);
}, function(error) {
console.log('error', error); // here is error from console: Object {data: null, status: -1, config: Object, statusText: "", headers: function}
});
}
getArticle01();
});
您重新定义articleId01这里:VAR articleId01 =主页。数据[0] .articleID;所以当你在另一个函数中需要它时,它不存在。也许使用范围变量? – Groben