MEAN 堆栈:通过 Web 服务向客户端发送字符串,无法访问我的字符串

MEAN stack: sending a string to client through a web service, can't access my string

如标题所说,我需要一个网络服务来将字符串发送回客户端。我会给你一个小代码示例。 这是我的路线文件:

/*log.js*/
            var express = require('express');
            var router = express.Router();

            router.get('/myRoute', function(req, res){
                var greeting = "Hello there!";
                res.json({"myMsg" : greetings});
            }

            module.exports = router;

这是我的 angular 控制器:

/*functions.js*/
            app.factory('greetFactory', function($resource){
                return $resource('/log/myRoute');
            });

            app.controller('GreetCtrl', function(greetFactory){
                this.getGreetings = function(){
                    var msg = greetFactory.get();
                    console.log(msg);
                    console.log(msg.myMsg);
                };
            });

该函数是通过在html文件中按下一个按钮来调用的,我不会举例说明那部分。问题是我无法从 msg 变量中获取参数 myMsg,这是程序打印的内容:

    e {$promise: d, $resolved: false, toJSON: function, $get: function, $save: function…}
        $promise: d
        $resolved: true
        myMsg: "Hello there!"
        __proto__: e
    undefined

我错过了什么吗?为什么我无法获取 属性 "myMsg" 的值?

编辑:对不起grammar/typing

您收到未定义的消息,因为在您调用 console.log(msg.myMsg) 时服务器尚未解析该请求。

根据官方Angular documentation

It is important to realize that invoking a $resource object method immediately returns an empty reference (object or array depending on isArray). Once the data is returned from the server the existing reference is populated with the actual data. This is a useful trick since usually the resource is assigned to a model which is then rendered by the view. Having an empty object results in no rendering, once the data arrives from the server then the object is populated with the data and the view automatically re-renders itself showing the new data. This means that in most cases one never has to write a callback function for the action methods.

The action methods on the class object or instance object can be invoked with the following parameters:

HTTP GET "class" actions: Resource.action([parameters], [success], [error]) non-GET "class" actions: Resource.action([parameters], postData, [success], [error]) non-GET instance actions: instance.$action([parameters], [success], [error])

所以从技术上讲,当您调用 $resource get 方法时不需要回调函数,但是您可以像这样添加一个:

this.getGreetings = function(){
    var msg = greetFactory.get(function() {
        console.log(msg.myMsg);
    });
    console.log(msg);
};