angularjs - 为什么我无法显示使用 $http.get 获取的数据?

标签 angularjs node.js express

我尝试在 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/

相关文章:

node.js - 如何在 Windows 上安装 MediaWiki Parsoid

javascript - 与 JavaScript 中 Python 的 chr() 对应

javascript - 需要在 JSON 格式的 API 输出中搜索值并打印整个数组内容

node.js - ExpressJS 无法通过 HTTPS 提供静态文件

javascript - AngularJS 对 JSON 中嵌套的数组进行排序

javascript - 如何从 Angular 自定义表单控制指令中获取 a 的父表单?

javascript - Node Express Passport 与 Angular - 不兼容?

node.js - Express 在 AppFog 上出错,但在本地则不然

javascript - 在 Controller 中无法使用 ng-repeat 在弹出窗口中显示内容?

javascript - AngularJS - 为值(value)增值