Calling nodeJS from angularJS function - angularjs

I have one function which block one room from room list via ajax call here is function
$scope.blockThisRoom = function(room, index){
// ajax call an validation
}
I have setup nodeJs script
var http = require('http');
var url = require('url');
var fs = require('fs');
var server;
var io = require('socket.io').listen(server);
server = http.createServer(function(req, res){
var queryObject = url.parse(req.url,true).query;
console.log(queryObject)
}),
and it gives query object while I am doing testing.
My Problem
I want to call nodeJS script when $scope.blockThisRoom function is call but I am confuse how to call node function.... , should I include nodeJS script as we add other javascript files in my view
or
I call nodeJS file a via ajax calling like below is code
$scope.testController = function() {
var url = "http://localhost:8076?id=1&type=block";
$http.get(url).success( function(response) {
$scope.students = response;
});
}

Angular and node are differents : NodeJs is executed in server, and angular in client. So If you try to include node script and run it on client browser, It will just not work... The two are javascripts, but not linked by any ways: you can use angular on PHP projects, and you can use Node.js without angular. It is just the fact that the two technologies are powerful when used together...
Effectively, I suggest to use Ajax call, with parameters you want (use $http.post instead of $http.get if you want to send a long query, or if you want to send arrays or objects... because with node and Angular post, you can send/parse JSON strings!!)

Related

Express Get api

I'm practicing right now with the MEAN stack.
I've made a project with the Angular shell and I've inclueded express in my project.
Here's my first GET, i want to use it to retrive some data from my mongoDB, in this case an entire collection:
router.get('/biscottigrazie', function(req, res) {
var db = req.db;
var collection = db.get('biscotti');
});
Maybe I'm missing the concept but i think that from angular i should be able to "call" this GET and get the data.
So, my var collection should contain the data, how can I retrive them from angular files?
You will not get db instance from request variable. You will get it while you define database.
var db = new Db('test', new Server('localhost', 27017));
router.get('/biscottigrazie', function(req, res) {
var collection = db.getCollection('biscotti');
res.send(collection);
});

How to send node js server side data to angular js

I am new to mean stack , in fact working on my very first project , i want to remember the request from the specific browser , which i have done using cookies . After that i want to send the history data from the server specific to every request which i am not able to do , as i couldnt find a suitable way . i tried using sessionstorage in angular js but that doesnt pull the session data i kept in node js ) Please let me know how is make it .
Node js:
when i have set session var titles here in node js
var chkck = function(req,res,next){
console.log("inside cookie callback .. ");
req.session.titles = req.session.titles || [];
//titles.push(req.params.)
req.session.titles.push("22");
res.sendFile("F:/customer/public/index.html");
}
app.use(chkck);
app.get('/',function(req,res){
res.sendFile("F:/customer/public/index.html");});
angular js:
but in angular , i am not able to retrieve the titles from sessionstorage .
var nameapp=angular.module('name-App',["ngRoute",'ngCookies','ngStorage']);
nameapp.controller('NameCtrl',
function($scope,$http,$window, $cookieStore,$sessionStorage ){
$scope.arr=[];
$scope.finddet=function(){
console.log("sessionstorage.titles"+ $sessionStorage.titles);
}});
this gives undefined
In your Nodejs code: convert your response to JSON
res.send(JSON.stringify(data));
Sample answer
AnguarJs:
In your controller file,
$http.get(/your_url).then(function(response){
// You will get the above response here in response.data
})

Restangular how to build custom url

with this code
RestangularProvider.setBaseUrl('http://localhost:8080/api/1');
var elements = Restangular.all('events');
elements.getList();
I can call the endpoint
http://localhost:8080/api/1/events
but how can manage the code to have
http://localhost:8080/api/1/events/around/me
You can use the following code, to get the events
var getEvents = Restangular.oneUrl('getEventAroundMe', 'http://localhost:8080/api/1/events/around/me');

Mean.io framework with socket.io

How to use socket.io in Mean.io stack?
First of all, Mean.io changes their folder structure very regularly.. So my question is where is the best place to configure socket.io ? or is it better to use express.io ?
Second I am still not quite sure where to look for to find code that tells mean.io to listen for port, I have found a port is defined in config folder in all.js file, but real problem is as soon as I define server.listen(port) app doesn't load. and if I don't app loads but socket.io doesn't work.
Also I have another question about /socket.io/socket-io.js file? I have copied that in index folder, but my app can't find it or says 404 error. I know it's not an actual file sitting on any such location as far as I have understood, also people suggested to put that line as 127.0.0.1/socket.io/socket-io.js but none made the js file available for the app to be able to run socket.io.
What is the proper way of defining socket.io in mean.io framework?
I also faced the same issue and took me about a week to finally get it right. I'll try to explain what I did:
app.js
In this file, I just invoke the code that creates and sets up a socket.io object for me, which is then passed to the routes module.
'use strict';
/*
* Defining the Package
*/
var Module = require('meanio').Module;
var MeanSocket = new Module('chat');
/*
* All MEAN packages require registration
* Dependency injection is used to define required modules
*/
MeanSocket.register(function(app, http) {
var io = require('./server/config/socketio')(http);
//We enable routing. By default the Package Object is passed to the routes
MeanSocket.routes(io);
return MeanSocket;
});
server/config/socketio.js
This file simply configures the socket.io object. Please note that I had to upgrade meanio module to version 0.5.26 for this work, as http object (express server) is not available in older meanio versions. Moreover, in case you want to use ssl, you can inject https instead of http.
'use strict';
var config = require('meanio').loadConfig(),
cookie = require('cookie'),
cookieParser = require('cookie-parser'),
socketio = require('socket.io');
module.exports = function(http) {
var io = socketio.listen(http);
io.use(function(socket, next) {
var data = socket.request;
if (!data.headers.cookie) {
return next(new Error('No cookie transmitted.'));
}
var parsedCookie = cookie.parse(data.headers.cookie);
var sessionID = parsedCookie[config.sessionName];
var parsedSessionID = cookieParser.signedCookie(parsedCookie[config.sessionName], config.sessionSecret);
if (sessionID === parsedSessionID) {
return next(new Error('Cookie is invalid.'));
}
next();
});
return io;
};
routes/chat.js
Finally, use the routes file to define the socket events, etc.
'use strict';
// The Package is passed automatically as first parameter
module.exports = function(MeanSocket, io) {
io.on('connection', function(socket) {
console.log('Client Connected');
socket.on('authenticate', function(data, callback) {
});
});
};
Hope this helps!
The simplest way would be to install the socket package...
mean install socket

How can I build a get request with url that contains parameters

I am trying to do a get request to recover data from the server using the following url:
url = /api/projects/:projectId/scenarios
How can I do that using $http.get in AdngularJS?.
you might want to take a look at Restangular, I like its notation more than standard angularjs $http or $resource.
Restangular.setBaseURL('/api/');
Restangular.one('projects', projectId).all('scenarios').getList().then(function(data) {
myVariable = data;
});
Restangular

Resources