json - 解析 JSON 并在 Angular 中显示数据

标签 json angularjs node.js express

我在 Angular 中显示 JSON 数据时遇到问题。我成功地将数据从后端发送到前端(Angular),但我无法显示它们。

我试图在 JSFiddle 上模拟类似的情况, 虽然我已经准备好后端的数据 following format

获取/发送数据 -> 后端:

//push data to Redis
var messages= JSON.stringify(
    [
        {
            "name": "Msg1",
            "desc": "desc Msg1"
        },
        {
            "name": "Msg2",
            "desc": "desc Msg2"
        },
        {
            "name": "Msg3",
            "desc": "desc Msg3"
        },
        {
            "name": "Msg4",
            "desc": "desc Msg4"
        }
    ]);
    redisClient.lpush('list', messages, function (err, response) {
        console.log(response);
    });

//get from redis and send to frontend
app.get('/messages', function(req, res){
    // Query your redis dataset here
    redisClient.lrange('list', 0, -1, function(err, messages) {
        console.log(messages);
       // Handle errors if they occur
       if(err) res.status(500).end();
       // You could send a string
       res.send(messages);
       // or json
       // res.json({ data: reply.toString() });
    });
});

获取数据 -> 前端(Angular)

angular.module('app')
    .controller('MainCtrl', ['$scope', '$http', function ($scope, $http) {
        'use strict';

        getFromServer();
        function getFromServer(){
          $http.get('/messages')
               .success(function(res){
                   $scope.messages= res;
                   console.log(res);
               });
        }
    }])

带有 ng-repeat 指令的 HTML 部分:

<div ng-app="app" ng-controller="MainCtrl" class="list-group">
    <div class="list-group-item" ng-repeat="item in messages">
        <h4 class="list-group-item-heading">{{item.name}}</h4>
        <p class="list-group-item-text">{{item.desc}}</p>
    <div>
</div>

有谁知道问题出在哪里?

最佳答案

据我所知,您将对象存储为 JSON,但您从不解析它。因此使用

$scope.messages = JSON.parse(res);

而不是

$scope.messages = res;

应该可以解决您的问题。

这是您的 JSFiddle 版本:https://jsfiddle.net/29y61wtg/5/

请注意,这不包括 $http 调用,如果您在使用 $http 后仍然遇到问题,请在评论中告诉我。

关于json - 解析 JSON 并在 Angular 中显示数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31415270/

相关文章:

javascript - 为什么 Typescript 认为 async/await 返回一个包含在 Promise 中的值?

javascript - 为什么我的 ng-view 动画不工作?

node.js - 在 NodeJs 中使用 Multer 上传文件时出错

c# - 使用 System.Runtime.Serialization.Json 反序列化 JSON

javascript - 访问 JSON 对象中的字段

angularjs - 无法访问 angular.js $cookies 对象

javascript - NodeJS 应用程序使用 Heroku 构建,但显示应用程序错误

arrays - 获取jq中的对象数组索引

json - 在 TableView 中显示 JSON

node.js - 未安装包裹