简体   繁体   中英

how to fetch the record from mongodb to part of html page automaticalyy without refreshing/reloading manually. using MEAN stack

Need some help reading Mean stack. I have a requirement like,

When a record is inserted into database, part of html page should get displayed with the new inserted record without reloading/refreshing manually.

Html page should get automatically updated with new record.

observations so far: I am already using angularjs, nodejs and mongodb. Using refresh() function, able to update part of hrml page manually. I am to insert the record from html page to mongodb.

You should use websockets ( socket.io is a good option ).

In the route responsible for document insertion/update on the backend, you should emit a new_document signal with the document's body to all sockets in the site...

Example:

 app.post('/api/posts', (req, res) => { Post.insert(postBody).then(body => { io.emit('new_document', body); // Broadcast to all websocket clients res.json(body); }).catch(err => { console.error(err); res.status(500).json({error: err.message}); }); }); 

Then, in the front-end, you should listen for the new_document event and call the refresh() function as callback or, even better, write a function to add just the new document.

Example:

 socket.on('new_document', function (body) { // ... code to add body to HTML ... }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM