【问题标题】:how to get realtime data in nodejs mongodb and angularjs using SocketsJs?如何使用 Sockets Js 在节点 js mongodb 和 angularjs 中获取实时数据?
【发布时间】:2019-07-31 19:46:15
【问题描述】:

我有一个 nodejs 服务器,它正在从 mongodb 获取集合列表。这是它的代码。因为我是套接字新手所以..

const express = require("express");
const app = express();
const http = require("http").Server(app);
const socketio = require('socket.io');

之后,我只是在路由中获取数据。还有一件事,所有代码都在一个文件中,我确实需要快速路线,因为应用程序中有其他路线。这是获取列表的mongodb代码

app.post("/getAllOfferManagement",
    async (req, res) => {
        try {
            MongoClient.connect(url,
                function(err, db) {
                    if (err) throw err;
                    var dbo = db.db("realtime");
                    dbo
                        .collection("offer")
                        .find({})
                        .toArray(function(err,
                            result) {
                            if (err) throw err;
                            // console.log('getting it ');
                            res.send(result);
                            db.close();
                        });
                });
        } catch (err) {
            res.send("error");
        }
    }); // its all working fine when i hit the route

http.listen(5000, function() {
    console.log("Server Started!");
});
//serversidecode ends here

现在我通过角度获取数据,这是它的代码

$scope.getAllOffer = function() {

    $scope.mongoloader = true;

    //nodejs api endpoint 
    $http.post("http://localhost:5000/getAllOffer").then(function(res) {
        $scope.offersArray = res.data;
        console.log('data here', res.data);
    });
};

以上工作正常。但我需要实时获取数据,例如当 somone 在 mongodb 中插入新文档时,视图会得到更新。我是套接字新手,因此不胜感激。谢谢

【问题讨论】:

    标签: node.js angularjs sockets websocket real-time


    【解决方案1】:

    为此,您必须在后端以及前端添加一个事件 后台

    io.on('connection', (socket) => {
    
        console.log(socket.id);
    
    
        socket.on('SEND_TITLE', function(data){
    
            io.emit('RECEIVE_TITLE', data);
    
            console.log('data',data)
    
        })
    
    });
    

    对于前端你必须使用 socket io 客户端模块

    import io from "socket.io-client";
    socket = io('your backend host url')
    
        socket.on('RECEIVE_TITLE', function(data)
          Console. Log(data);
    
      });
    

    前端语法可能在角度上有所不同。 因为我不熟悉角度

    欲了解更多信息,请访问。

    对于客户端。

    https://socket.io/docs/client-api/

    对于服务器。

    https://socket.io/docs/server-api/

    【讨论】:

    • 非常感谢您的回复。但我有一个 api 路线。我只需要在那个 api 端点上使用套接字。我不知道如何在快速路由中使用套接字
    • 我认为这会对您有所帮助。 [stackoverflow.com/questions/47837685/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-15
    • 1970-01-01
    • 2019-09-18
    • 1970-01-01
    • 2019-10-06
    • 2019-12-05
    相关资源
    最近更新 更多