我尝试在 api 中获取数据,并在 console.log 中获取对象,如下所示:
Object {_id: "590c14b1bf38e524e4b1a1ca", name: "John", age: 22, __v: 0}
这是我用来获取它并显示的代码。
服务器
detailRoute.route('/detail/:name')
.get(function(req,res) {
User.findOne({name:req.params.name},function(err,user) {
console.log(user);
if (err){
res.status(404).send(err);
}else{
res.status(200).json(user);
}
})
});
js:
var vm = this;
vm.dt =[];
vm.getDetail = function() {
$http.get('/api/detail/' + $stateParams.dt , $stateParams.dt)
.then(function(response) {
vm.dt = response.data;
console.log(response.data);
});
};
vm.getDetail();
html:
<ul ng-repeat="d in vm.dt">
<li>{{d.name}}</li>
<li>{{d.age}}</li>
</ul>
什么也没有显示。我尝试更改为
vm.dt.push(response.data)
它成功了。所以我想问为什么我上面的代码不起作用。感谢您的帮助
最佳答案
http
调用的输出是一个对象。
您正在将现有数组引用 vm.dt
重写为回调内的对象,然后尝试循环遍历模板内的数组。
尝试以字典方式更改ng-repeat
。
<ul ng-repeat="(key, value) in vm.dt">
<li>{{key}} {{value}}</li>
</ul>
I try change to vm.dt.push(response.data) And it worked.
因为这样你仍然使用数组,并且 ng-repeat 会起作用
要仅过滤姓名和年龄,您可以使用 ng-if
或自定义过滤器
<ul ng-repeat="(key, value) in vm.dt" ng-if="key === 'name' || key === 'age'">
<li>{{key}} {{value}}</li>
</ul>
关于angularjs - 为什么我无法显示使用 $http.get 获取的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43801487/