Angular GET请求被困在循环中

时间:2016-02-07 23:15:53

标签: angularjs node.js postgresql express

我正在尝试使用angular来向我发布的api发出请求,检索并操作Postgres数据库中的数据。我有两个本网站的运行副本,一个使用Mongo。下面的问题代码在使用Mongo的服务器上正常运行但由于某种原因Postgres正在遇到麻烦。当我使用REST客户端测试api时,两个版本都可以工作(Mongo和Postgres),这让我相信api不是问题所在。但是,我的主页面包含一个角度控制器,它向api发出GET和POST请求。就像我说的,这个循环发生的唯一时间是在Postgres的服务器上。

这是有问题的控制器:

(function() {

    var PostCtrl = function ($http, $scope, $log, $location) {

        $scope.getPosts = function() {
            $http.get("api/posts")
                .then(function(response) {
                    $scope.posts = response.data;
                });
        }

        $scope.addPost = function(title, content, image) {
            $http.post("api/posts", {title: title, content: content, image: image})
                .error(function(data) {
                    console.log(data);
                });
            //$scope.getPosts();
        }


        //$scope.getPosts();
    };

    app.controller("PostCtrl", ["$http", "$scope", "$log", "$location", PostCtrl]);

})();

以下是我使用控制器的页面:

extends partials/layout

block scripts
    script(src="app/controllers/PostCtrl.js")

block content
    div(ng-controller="PostCtrl")
        .row
            .col-xs-9
                #main
                    .row
                        .col-xs-12
                            form(class="form-horizontal" ng-submit="post(title, content, image)")
                                .form-group
                                    label(for="inputTitle" class="col-sm-2 control-label") Title
                                    .col-sm-10
                                        input(required type="text" class="form-control" id="inputTitle" placeholder="Title" ng-model="title")
                                .form-group
                                    label(for="inputContent" class="col-sm-2 control-label") Content
                                    .col-sm-10
                                        textarea(required class="form-control" id="inputContent" placeholder="Content" ng-model="content")
                                .form-group
                                    label(for="inputImg" class="col-sm-2 control-label") Image URL
                                    .col-sm-10
                                        input(required type="text" class="form-control" id="inputImg" placeholder="Image URL" ng-model="image")
                                .form-group
                                    .col-sm-offset-2.col-sm-10
                                        button(type="submit" class="btn btn-default") Post

                    .row
                        .col-xs-12
                            div(ng-repeat="post in getPosts()")
                                hr
                                .well
                                    h2 {{ post.title }}
                                    h4 {{ post.content }}
                                    img(src="{{ post.image }}")

            .col-xs-3
                .row
                    .col-xs-12
                        #sidebar
                            .well(style="height: 500px;")

block footer
    .row
        .col-xs-12
            hr
            .footer
                h4(class="copyright") Footer

这是以下的API:

var express = require("express");
var router = express.Router();
var pg = require("pg");

var dbUrl = "postgres://usr:pwd@localhost:5432/vagablog";

// Middleware for all routes.
router.use(function(req, res, next) {
    console.log("API request made.");
    next(); // Go to next routes, don't stop here
});

// Test route to ensure routing is working
router.get("/", function(req, res) {
    res.json({
        message: "Hooray! Welcome to the API!"
    });
});

// On routes that end in /posts
router.route("/posts")

    // Get all posts. (Accessed at GET api/posts)
    .get(function(req, res) {

        // Connect to DB
        var client = new pg.Client(dbUrl);
        client.connect();
        console.log("Client connected to DB");

        // Select all from post table
        var query = client.query("select * from post");

        // Send response on failed query with error
        query.on("error", function(error) {
            res.send({
                status: "failed",
                reason: error
            });
        });

        // Add each row to result
        query.on("row", function(row, result) {
            result.addRow(row);
        });

        // Send response on successful query with results
        query.on("end", function(result) {
            client.end();
            res.send(JSON.stringify(result.rows));
        });

    })

    // Create post. (Accessed at POST api/posts)
    .post(function(req, res) {

        // Connect to DB
        var client = new pg.Client(dbUrl);
        client.connect();
        console.log("Client connected to DB");

        // Check if needed request body items are valid
        if(req.body.title !== undefined && req.body.content !== undefined) {

            // Perform insert query
            var query = client.query("insert into post (title,content) "+
            "values ('"+req.body.title+"','"+req.body.content+"')");

            // Send response on failed query
            query.on("error", function(error) {
                client.end();
                res.send({
                    status: "failed",
                    reason: error
                });
            });

            // Send response on successful query
            query.on("end", function(result) {
                client.end();
                res.send({
                    status: "success",
                    title: req.body.title,
                    content: req.body.content,
                    image: req.body.image
                });
            });

        // Send response if missing request body item
        } else {
            res.send({
                status: "failed",
                reason: "Could not find one or more of parameters: title, content, image"
            });
        }

    });

router.route("/posts/:post_id")

    // Get post. (Accessed at GET api/posts/:post_id)
    .get(function(req, res) {
        // TODO Get post
    })

    // Update post. (Accessed at PUT api/posts/:post_id)
    .put(function(req, res) {
        // TODO: Update post
    })

    // Delete post. (Accessed at DELETE api/posts/:post_id)
    .delete(function(req, res) {

        // Connect to DB
        var client = new pg.Client(dbUrl);
        client.connect();
        console.log("Client connected to DB");

        // Delete from post table where id is equal to :post_id
        var query = client.query("Delete from post Where id ="+req.params.post_id);

        // Send response on successful deletion with error
        query.on("end", function(result) {
            client.end();
            res.send({
                status: "success"
            });
        });

        // Send response on failed deletion with error
        query.on("error", function(error) {
            client.end();
            res.send({
                status: "failed",
                reason: error
            });
        });

    });

// TODO: Create api routes for table deletion/clearing/creation

module.exports = router;

服务器输出:

GET /api/posts 200 20.691 ms - 73
GET /api/posts 200 22.513 ms - 73
GET /api/posts 200 25.023 ms - 73
API request made.
Client connected to DB
GET /api/posts 200 17.603 ms - 73
GET /api/posts 200 19.947 ms - 73
GET /api/posts 200 13.149 ms - 73
API request made.
Client connected to DB
API request made.
Client connected to DB
GET /api/posts 200 12.391 ms - 73
API request made.
Client connected to DB
API request made.
Client connected to DB
API request made.
Client connected to DB
API request made.
Client connected to DB
GET /api/posts 200 16.033 ms - 73
API request made.
Client connected to DB
API request made.
Client connected to DB
GET /api/posts 200 17.256 ms - 73
GET /api/posts 200 18.421 ms - 73
GET /api/posts 200 18.786 ms - 73
GET /api/posts 200 19.534 ms - 73
API request made.
Client connected to DB
API request made.
Client connected to DB
GET /api/posts 200 16.590 ms - 73
GET /api/posts 200 19.997 ms - 73
API request made.
Client connected to DB
GET /api/posts 200 15.494 ms - 73
GET /api/posts 200 18.389 ms - 73
API request made.
Client connected to DB
API request made.
Client connected to DB
API request made.
Client connected to DB
API request made.
Client connected to DB
API request made.
Client connected to DB
GET /api/posts 200 14.374 ms - 73
API request made.
Client connected to DB
API request made.
Client connected to DB
API request made.
Client connected to DB
GET /api/posts 200 18.409 ms - 73
GET /api/posts 200 19.716 ms - 73
API request made.
Client connected to DB
GET /api/posts 200 21.166 ms - 73
API request made.
Client connected to DB
GET /api/posts 200 23.422 ms - 73
GET /api/posts 200 23.104 ms - 73
API request made.
Client connected to DB
API request made.
Client connected to DB
API request made.
Client connected to DB
GET /api/posts 200 23.240 ms - 73
GET /api/posts 200 23.442 ms - 73
API request made.
Client connected to DB
GET /api/posts 200 26.767 ms - 73
GET /api/posts 200 20.711 ms - 73
GET /api/posts 200 18.902 ms - 73
API request made.
Client connected to DB
API request made.
Client connected to DB
GET /api/posts 200 20.807 ms - 73
GET /api/posts 200 22.459 ms - 73
GET /api/posts 200 23.733 ms - 73
GET /api/posts 200 20.734 ms - 73
API request made.
Client connected to DB
API request made.
Client connected to DB
GET /api/posts 200 19.195 ms - 73
GET /api/posts 200 19.811 ms - 73
API request made.
Client connected to DB
API request made.
Client connected to DB
API request made.
Client connected to DB
GET /api/posts 200 14.928 ms - 73
GET /api/posts 200 15.960 ms - 73
API request made.
Client connected to DB
API request made.
Client connected to DB
API request made.
Client connected to DB
GET /api/posts 200 18.811 ms - 73
GET /api/posts 200 20.031 ms - 73
GET /api/posts 200 22.332 ms - 73
API request made.
Client connected to DB
GET /api/posts 200 19.272 ms - 73
GET /api/posts 200 19.888 ms - 73
GET /api/posts 200 20.281 ms - 73
API request made.
Client connected to DB
API request made.
Client connected to DB
API request made.
Client connected to DB
API request made.
Client connected to DB
API request made.
Client connected to DB
API request made.
Client connected to DB
API request made.
Client connected to DB
GET /api/posts 200 18.424 ms - 73
API request made.
Client connected to DB
GET /api/posts 200 22.150 ms - 73
API request made.
Client connected to DB
GET /api/posts 200 23.577 ms - 73
GET /api/posts 200 24.877 ms - 73
GET /api/posts 200 27.099 ms - 73
API request made.
Client connected to DB
API request made.
Client connected to DB
GET /api/posts 200 26.699 ms - 73
GET /api/posts 200 28.815 ms - 73
GET /api/posts 200 29.594 ms - 73
API request made.
Client connected to DB
API request made.
Client connected to DB
API request made.
Client connected to DB
API request made.
Client connected to DB
GET /api/posts 200 24.583 ms - 73
API request made.
Client connected to DB
GET /api/posts 200 24.909 ms - 73
GET /api/posts 200 21.310 ms - 73
API request made.
Client connected to DB
API request made.
Client connected to DB
GET /api/posts 200 25.254 ms - 73
API request made.
Client connected to DB
GET /api/posts 200 22.883 ms - 73
GET /api/posts 200 24.659 ms - 73
GET /api/posts 200 27.842 ms - 73
GET /api/posts 200 23.009 ms - 73
GET /api/posts 200 31.817 ms - 73
API request made.
Client connected to DB
API request made.
Client connected to DB
API request made.
Client connected to DB
GET /api/posts 200 22.164 ms - 73
GET /api/posts 200 25.102 ms - 73

1 个答案:

答案 0 :(得分:0)

如果Angular认为您的任何模型发生了变化,或者如果发生触发摘要周期的任何事情(这可能不是100%正确的措辞,这里的任何输入都被赞赏),函数将始终重新运行。

    $scope.getPosts = function() {
        $http.get("api/posts")
            .then(function(response) {
                $scope.posts = response.data;
            });
    }

    $scope.addPost = function(title, content, image) {
        $http.post("api/posts", {title: title, content: content, image: image})
            .error(function(data) {
                console.log(data);
            });
        //$scope.getPosts();
    }

当角度认为模型发生变化时,上面将始终尝试运行。

你应该试试

$scope.posts = [];

$http.get("api/posts").then(function (response) {
    $scope.posts = response.data;
});

$scope.addPost = function(title, content, image) {
    $http.post("api/posts", {title: title, content: content, image: image})
        .then(function (response) { 
                 //success
                 console.log(response.data); 
              }, 
              function (response) { 
                 //error
                  console.log(response.data);
              });