不能多次调用 $http.get()

Can't call $http.get() more than once

完成问题修改

既然这个问题已经演变成完全不同的东西,我想我还是从头再来解释一下现在的情况吧。

我正在尝试使用 Node、Express、MongoDB 和 Angular 创建一个简单的留言板。

我有一个 get 和 post 函数,它们在服务器端似乎工作正常,我没有收到任何错误,我的数据正在 added/retrieved to/from 数据库中。

问题出在我的客户端 getMessages() 函数上。

在正常情况下,我想在网站初始化时调用 getMessages(),并在 post 发送消息后调用。但为简单起见,我创建了一个按钮,按下时调用 "getMessages()"。

我第一次按下这个按钮时,一个 GET 请求被发送出去,我的所有消息都被检索并显示在视图中。

但是当我 post 一条消息,并再次点击 'get-messages-button' 时,没有新的 GET 请求被发送出去,函数 returns 旧列表(检索到的那个第一个也是唯一一个 GET 请求)

我已经坚持了 3 天了,我真的不明白我做错了什么。正在调用 getMessages() 函数,但它似乎将第一个 GET 请求的 'response.data' 存储在某处并立即 returns 相同的数据,而没有机会发送新的 GET 请求。

代码:

控制器

(function() {
'use strict';

angular
.module('app')
.controller('MainController', mainController);

function mainController(navigationFactory, $http, $timeout, apiFactory, $scope) {

    var that = this; // jshint ignore: line

    function init() {
        //that.getMessages();
    }

    that.getMessages = function() {
        return apiFactory.getMessages().then(function(messages) {
            that.messages = messages;

        });
    }

    that.postMessage = function() {

        apiFactory.postMessage(that.message).then(function(response) {
            console.log('Posted from controller', response);               
        }).catch(function(e) {
            console.log(e);
        });

    }

    init();   
}
})();

服务

(function() {
'use strict';

angular
    .module('app')
    .factory('apiFactory', apiFactory);

function apiFactory($interval, $localStorage, $sessionStorage, $http) {

    var factory = {};

    factory.postMessage = function(message) {
        return $http.post('http://localhost:5000/api/message', {msg: message}).then(function(response) {
                return response;
        });       
    }

    factory.getMessages = function() {
        var promise = $http.get('http://localhost:5000/api/message').then(function(response) {
                console.log('data:', result.data); //Immediately returns old list without sending new GET request
                return response.data;
        });    

        return promise;        
    }

    return factory;
}

})();

Server.js(以防万一结果是我的服务器端代码)

var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');


var Message = mongoose.model('Message', {
    msg: String
});
var app = express();


app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Content-Type, Authorization");
    next();
})

app.get('/api/message', GetMessages);

app.post('/api/message', function(req, res) {
    console.log(req.body);

    var message = new Message(req.body);
    message.save(function(err) {
        if(err) {
            console.log(err);
        } else {
            res.status(200).send('Message added');
        }
    }); 
})

function GetMessages(req, res) {
    console.log('Getting messages from server');
    Message.find({}).exec(function(err, result) {
        if(err) {
            return res.status(500).send(err);
        }
        return res.status(200).json(result);
    });

    console.log('Got messages from server');
}

mongoose.connect("mongodb://localhost:27017/mydb", function(err, db) {
    if(!err) {
        console.log("Connected to mongoDB!");   
    }
})

var server = app.listen(5000, function() {
    console.log('listening on port ', server.address().port);
})

更新

这可能有助于说明问题的确切原因。

我有一个函数,当我在我的视图上按下按钮时调用:

    that.getMessages = function() {
         $http.get('http://localhost:5000/api/message'); // <-- Only happens once
         console.log('get request sent'); // <-- Gets logged everytime 
    };

我所做的只是向我的服务器发送一个获取请求。还没有承诺。 第一次按下我的按钮时,我可以在我的调试器网络选项卡中看到一个 GET 请求,它的状态为 304 和我的消息数组的响应。

现在,当我第二次按下按钮时,没有发送 GET 请求。我可以记录消息,所以我知道我的函数正在被调用,但它似乎忽略了我的 $http.get()...

您的代码会在您 post 编辑新消息后立即获取消息。所以你不能保证第二个请求会在第一个请求之后被服务器处理。它们很有可能会被同时处理。您需要在处理 post 之后获取消息,即当对第一个请求的异步响应返回时。

因此,首先,您需要能够知道 post 何时成功。因此,您需要 return http 承诺,以了解它是已解决还是已拒绝:

factory.postMessage = function(message) {
    return $http.post('http://localhost:5000/api/message', {msg: message});
}

然后你需要在成功后获取消息post:

that.postMessage = function() {
    apiFactory.postMessage(this.message).then(function() {
        that.getMessages();
    });
}