0

I'm trying to create a simple messageboard with MongoDB, Angular, NODE.js and Express.

For some reason the first time I call getMessages() everything goes fine. But when I call getMessages() after a postMessage(), no GET request is being send.

These are my Routes:

app.get('/api/message', function(req, res) {
    Message.find({}).exec(function(err, result) {
        res.send(result);
    });
});

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

     var message = new Message(req.body);
     message.save();

     res.status(200).send('Message added');
})

And this is my angular controller:

(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.postMessage = function() {

        apiFactory.postMessage(that.message).then(function() {
            console.log('Posted from controller'); //gets logged
            that.getMessages(); 
        });
        //that.getMessages(); <-- also tried this

    }

    that.getMessages = function() {
        console.log('Getting from controller'); //gets logged
        $http.get('http://localhost:5000/api/message').then(function(result) {
                console.log(result.data); //Logs old result, without new message
                that.messages = result.data;
               console.log('Set data'); //gets logged
        });   
    }

     init();

}
})();

And finally I use a factory to post the message:

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

I already opened a similar question, but since this has turned out to be a different problem I thought I'll ask it again.

Why is there no HTTP GET Request, even though getMessages() is clearly being called in my postMessage() function. I can see that getMessages() is being called with the help of console.log(), but it seems to return before any request is being sent out.

Max Taylor
  • 343
  • 3
  • 16
  • Are you getting any console error ? – Manish Singh Nov 08 '16 at 11:36
  • No errors at all, I can see my POST request in the network tab, with status 200, but the GET request is not being sent. (only the first time when website is launched) – Max Taylor Nov 08 '16 at 11:37
  • Will you please try to create a fiddle ? – Manish Singh Nov 08 '16 at 11:40
  • 'Posted from controller' gets logged in console ? – Manish Singh Nov 08 '16 at 11:40
  • Yes, I tried adding loads of console.log()'s, and everything is running: postMessage() reaches .then statement --> getMessages() logs console before request, and after request. Even inside the .then() I can do a console.log(result.data); and it will send me the data, but it it's an old list, without the new message – Max Taylor Nov 08 '16 at 11:43
  • I thought the .then() only fires AFTER the $http.get() is finished. Then why am I not sending a GET request, but I am reaching .then() statement. – Max Taylor Nov 08 '16 at 11:44
  • The way you are saving in database might returning an error.. try using: message.save(function (err) { if (err) { return err; } else { console.log("message saved"); } }); – Manish Singh Nov 08 '16 at 11:49
  • I tried this, but no error is being throwed. Everytime I add a message, i get logged 'message saved'. And the message is in my database now. – Max Taylor Nov 08 '16 at 12:23

2 Answers2

1

I think you may be running into a hoisting issue, basically calling a function that hasn't yet been declared. What happens if you try changing the order like this?

var that = this; // jshint ignore: line

that.getMessages = function() {
    console.log('Getting from controller'); //gets logged
    $http.get('http://localhost:5000/api/message').then(function(result) {
            console.log(result.data); //Logs old result, without new message
            that.messages = result.data;
           console.log('Set data'); //gets logged
    });   
}

that.postMessage = function() {

    apiFactory.postMessage(that.message).then(function() {
        console.log('Posted from controller'); //gets logged
        that.getMessages(); 
    });
    //that.getMessages(); <-- also tried this

}

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

init();

var functionName = function() {} vs function functionName() {}

EDIT:

I fixed up your plunkr and it seems to be working just fine!

The issue was that you're not injecting $http into your controller... That's why your GET request never happened

https://plnkr.co/edit/NyI1qa63NG8gFfuc45jj?p=preview

Community
  • 1
  • 1
Moshe Karmel
  • 459
  • 4
  • 9
  • Nice catch, unfortunately nothing changed when I tried this :( – Max Taylor Nov 08 '16 at 14:04
  • Can you make a JSFiddle then? – Moshe Karmel Nov 08 '16 at 14:08
  • Is it possible to create a MEAN application with jsfiddle? – Max Taylor Nov 08 '16 at 14:09
  • What if you try adding a "return" to the getMessages function, like `return $http.get...` – Moshe Karmel Nov 08 '16 at 14:14
  • I'll try to create a jsfiddle.. but what you see there is basically all my relevant angular code. normally my getMessages is also located in the apiFactory, but I added it to the controller so the post wouldnt get too long. adding return to the function doesn't change anything... I have tried loads of different ways to do this and read many articles on promises, but the HTTP Get request is never sent, even when manually triggering the getMessages() function with a button. the GET request is literally only sent when I refresh the website – Max Taylor Nov 08 '16 at 14:24
  • Here is a non-functional plunker (Kinda defeats the purpose but oh well) : https://plnkr.co/edit/ti1xKI1NE5XjlKblDShh?p=preview – Max Taylor Nov 08 '16 at 14:51
  • Nope.. sorry, the plunkr didnt look at all at my code I just tried to recreate it quickly in 1 file but forgot the injections.. On my real code I have $http injected. How else would my first GET request work fine – Max Taylor Nov 09 '16 at 20:02
  • I figured out the problem... in my angular config stage for some reason I was enabling http caching. I turned this off and the problem was gone. Thanks for your help! – Max Taylor Nov 09 '16 at 21:38
1

I think, issue is at server side promise, Try using this.

app.get('/api/message', function(req, res) {
    return Message.find({}).exec(function(err, result) {
        if(err) {
          return res.status(500).send(err);
        }
        return res.status(200).json(result);
    });
});
Manish Singh
  • 518
  • 3
  • 13
  • Still didn't change anything, once again: my post and get are fully functional. I get no errors. The problem lies with that when my factory.getMessages() gets called, it immediately returns the old response, without even triggering a new GET request. – Max Taylor Nov 09 '16 at 09:15
  • Can you share your screen via teamviewer ? – Manish Singh Nov 09 '16 at 17:04
  • 1
    I figured out the problem... in my angular config stage for some reason I was enabling http caching. I turned this off and the problem was gone. Thanks for your help! – Max Taylor Nov 09 '16 at 21:38