【问题标题】:How to build connection with Angular.js and Node.js trough services?如何通过服务与 Angular.js 和 Node.js 建立连接?
【发布时间】:2015-11-22 22:48:03
【问题描述】:

我有一个简单的管理面板,里面有表格。我正在尝试通过 Angular.js 和 Node.js 连接更新此表单的内容。如果我做到这一点:我将能够读取表单的数据并在首页上呈现。

此表单从以下位置读取数据:“/json/form-data.json”

[{
  "name"    : "BigTitleLine1",
  "content" : "APP TITLE 1"
}, {
  "name"    : "BigTitleLine2",
  "content" : "APP TITLE 2"
}];

Angular Service 从该 json 文件中获取数据:

ServiceModule.factory('serviceFormData', ['$resource', function ($resource) {
    return $resource(rootPath("/json/form-data.json"), {}, {
        query: {
            method: 'GET',
            isArray: true
        }
    });
}]);

Angular Controller 将数据分配给模型:

ctrl.controller('formCtrl', ['$scope', '$rootScope', 'serviceFormData',
    function($scope, $rootScope, serviceFormData) {

        $scope.model = {};
        serviceFormData.query(function(data) {
            $scope.model.formData = data;
        });
]);

我可以在 HTML 上显示真实数据,并将更改保存到模型:

<form>
      <div class="form-group" ng-repeat="item in model.formData">
          <label>- {{ item.name }}</label>
          <input class="form-control" ng-model="item.content" required />
          <br />
      </div>
</form>

我在本地主机上创建了一个 Node.JS Express 服务器。它也可以读写文件。

var express = require('express'),
    fs      = require('fs'),
    app     = express();

app.use(express.static(__dirname));

// i can create "localhost:3000/test" page and show this json data over there
app.get('/test', function (req, res, next) {
    res.json({ some: "aq literal" });
});

// i can create "./json/test.json" file and write what i want.
fs.writeFile("./json/test.json", "Hey there!", function(err) {
    if(err) {
        return console.log(err);
    }
});

var server = app.listen(3000);

我正在尝试编写一个 json 文件,其中包含提交的 Angular 表单的模型。 像这样:

[{
  "name"    : "BigTitleLine1",
  "content" : "I've edited this json from my angular form which is on the client side."
}, {
  "name"    : "BigTitleLine2",
  "content" : "APP TITLE 2"
}];

如何在 Angular.js 和 Node.js 之间建立这种联系?

【问题讨论】:

    标签: javascript json angularjs node.js express


    【解决方案1】:

    您应该更改您的工厂以处理对 Node 的新调用以更新文件(或创建新工厂):

    ServiceModule.factory('serviceFormData', ['$resource', function ($resource) {
        return $resource('/update', {}, {
            update: {
                method: 'PUT'
            }
        });
    }]);
    

    那么你应该用 update 方法更新 Angular 控制器:

    var json = new serviceFormData.update($scope.item);
    
    json.$update(function (response) {
        $scope.success = true;
    }, function (response) {
        $scope.error = response;
    });
    

    最后你应该用新的路由来处理它:

    var bodyParser = require('body-parser');
    
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: true }));
    
    app.put('/update', function (req, res) {
      var arr = []
        for (var index in req.body){
          arr.push(req.body[index])
        }
        var jsonData = JSON.stringify(arr, null, 2);
    
        fs.writeFile("./json/test.json", jsonData, function(err) {
           if(err) {
              return console.log(err);
           }
           res.json({ success: true });
        });
    });
    

    我没有测试它,但这是要走的路。

    【讨论】:

    • 非常感谢您的回答,+1。我已经在 angular 和 node.js 之间建立了联系,但我无法正确写入数组数据,i've write another question for this,我正在接受你的答案。再次感谢。
    • 嗯,如果您在将数据发送到 Node 之前 console.log ,它是数组还是对象?
    • 它是一个数组,就像它的原始数组一样。
    • 请将工厂改成:update: { method: 'PUT', isArray: true }
    猜你喜欢
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-11
    • 1970-01-01
    相关资源
    最近更新 更多