How to pass $scope variables into the Node.js server using $resource - angularjs

I have $scope.todos and in my controller the code for submitting that is
$scope.submitChanges = function() {
var todos = $resource("/todo");
//code goes here for sending variable
}
And I want to send it to Node.js , which takes it as :
router.post("/",function(req, res) {
var collection = db.get("todo");
collection.insert({ /* here comes the data to insert */ }, function(err, todos) {
if(err) throw err;
res.json(todos);
})
})

var CreditCard = $resource('/todos/:Id',
{userId:123, Id:'#id'}, {
charge: {method:'POST', params:{charge:true}}
});

Related

Save and display comment in real-time using angularjs and socket.io

I have problem with socket.io. In my code router.post(/comment,...) saving user comments in database (using mongoose) and I am trying emit this save. In controller function readMoreCourse is to get and display all comments from database (and question how use socket to this function that using ng-reapat display comment in real-time). Function AddComment is on client side chceck valid form and next post comment to database.
My question: How in real-time save and display user comment using angular (ng-repeat?) and socket.io? Honestly I making this first time, and I have short time, thanks for any help.
Server
io.on('connection', function(socket){
socket.emit('comment', function(){
console.log('Comment emitted')
})
socket.on('disconnect', function(){
})
})
API
router.post('/comment', function(req, res) {
Product.findOne({ _id: req.body._id }, function(err, product){
if(err) {
res.json({ success:false, message: 'Course not found' })
} else {
User.findOne({ username: req.decoded.username }, function(err, user){
if(err){
res.json({ success:false, message: 'Error'})
} else {
product.comments.push({
body: req.body.comment,
author: user.username,
date: new Date(),
});
product.save(function(err){
if(err) throw err
res.json({ success: true, message: 'Comment added })
**io.emit('comment', msg);**
})
}
})
}
})
})
controller
Socket.connect();
User.readMoreCourse($routeParams.id).then(function(data){
if(data.data.success){
app.comments = data.data.product.comments;
} else {
$window.location.assign('/404');
}
});
app.AddComment = function(comment, valid) {
if(valid){
var userComment = {};
userComment.comment = app.comment;
Socket.on('comment', User.postComment(userComment).then(function(data){
if(data.data.success){
$timeout(function(){
$scope.seeMore.comment = '';
},2000)
} else {
app.errorMsg = data.data.message;
}
}));
} else {
app.errorMsg = 'Error';
}
}
$scope.$on('$locationChangeStart', function(event){
Socket.disconnect(true);
})
factory
userFactory.readMoreCourse = function(id) {
return $http.get('/api/seeMore/' + id)
}
userFactory.postComment = function(comment){
return $http.post('/api/comment', comment);
}
.factory('Socket', function(socketFactory){
return socketFactory()
})
In your socket factory, initialize socket.io emit and on events.
app.factory('socket', ['$rootScope', function($rootScope) {
var socket = io.connect();
return {
on: function(eventName, callback){
socket.on(eventName, callback);
},
emit: function(eventName, data) {
socket.emit(eventName, data);
}
};
}]);
and call this from controller
app.controller('yourController', function($scope, socket) {
User.postComment(userComment).then(function(data){
if(data.data.success){
$timeout(function(){
$scope.seeMore.comment = '';
},2000);
// Emit new comment to socket.io server
socket.emit("new comment", userComment);
} else {
app.errorMsg = data.data.message;
}
});
// other clients will listen to new events here
socket.on('newComment', function(data) {
console.log(data);
// push the data.comments to your $scope.comments
});
from socket.io server
io.on('connection', function(socket) {
// listen for new comments from controller and emit it to other clients
socket.on('new comment', function(data) {
io.emit('newComment', {
comment: data
});
});
});
EDIT:
If you just want to push from server side,
io.on('connection', function(socket) {
// after saving your comment to database emit it to all clients
io.emit('newComment', {
comment: data
});
});
and remove this emit code from controller:
socket.emit("new comment", userComment);
But this method can be tricky because the user who posts the comment should immediately see the comment added to the post. If you let socket.io to handle this there will be a few seconds lag for the guy who posted the comment.

How to pass $scope variable data into node.js backend server file?

I have json data in $scope variable and i want to use that $scope variable inside my backend app.js node file.
This is my backend file app.js:
app.post('/upload', upload.single('file'), function(req, res) {
var XLSX = require('xlsx');
var workbook = XLSX.readFile('./uploads/' + req.file.filename);
var sheet_name_list = workbook.SheetNames;
var data = XLSX.utils.sheet_to_json(workbook.Sheets[sheet_name_list[0]]);
//var values = [];
console.log(data);
return res.status(200).send(data);
});
app.post('/api/uploadlast',api.addNewContact, function(req,res){
Contact.bulkCreate(excels).then(function(users) {
return res.status(200).send(users);
}).catch(Sequelize.ValidationError, function(err) {
return res.status(422).send(err.errors[0].message);
}).catch(function(err) {
return res.status(400).send(err.message);
});
})
This is my controller file:
$scope.uploadFile = function() {
var file = $scope.myFile;
var uploadUrl = "/upload";
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {
'Content-Type': undefined
}
})
.then(function(response) {
//$state.reload();
$scope.excels = response.data;
console.log("success!!");
})
.catch(function() {
console.log("error!!");
});
}
$scope.uploadLast = function() {
$http.post('/api/uploadlast').then(function(response) {
$state.reload();
});
}
})
I want to get $scope.excels data into my backend to bulkcreate into databases.
You can pass any data with a post request as the second parameter of $http.post(). So you can do something like:
$scope.uploadLast = function() {
var data = {
excels: $scope.excels
};
$http.post('/api/uploadlast', data).then(function(response) {
$state.reload();
});
}
And in your backend, you can access it like:
app.post('/api/uploadlast',api.addNewContact, function(req, res){
var data = req.body.excels;
Contact.bulkCreate(data).then(function(users) {
return res.status(200).send(users);
}).catch(Sequelize.ValidationError, function(err) {
return res.status(422).send(err.errors[0].message);
}).catch(function(err) {
return res.status(400).send(err.message);
});
});

pass data from PouchDB Service to Controller in AngluarJS

I have set up a PouchDb service in Angular/Ionic which works fine within the service, but fails when I try to pass the data I retrieve from PouchDB service to my controller.
this is my service
angular.module('myApp', [])
.service('DBService', function($q) {
var items;
var db;
var self = this;
this.initDB = function() {
return db = new PouchDB('simpleDB', {
adapter: 'websql'
});
};
this.storeData = function() {
return $q.when(
db.put({
_id: 'mydoc',
title: 'some text'
}).then(function (response) {
// handle response
console.log('done')
}).catch(function (err) {
console.log(err);
})
)
};
this.getData = function(){
return $q.when(
db.get('mydoc').then(function (doc) {
// handle doc
console.log(doc); // I see the data in console
}).catch(function (err) {
console.log(err);
})
)
}
})
and this is the controller
angular.module('myApp', [])
.controller('mainCtrl', function($scope, DBService, $q) {
$scope.getData = function(){
DBService.initDB()
DBService.getData().then(function(data){
console.log(data)
})
}
when I use then() I get error TypeError: Cannot read property 'then' of undefined.
Can anyone help me figure out how I can pass the data correctly from my service to the controller?
I was lucky to find the error quickly! I was not returning the data in my service so I changed it to
this.getData = function(){
return $q.when(
db.get('mydoc').then(function (doc) {
// handle doc
return doc; // I added this
console.log(doc); // I see the data in console
}).catch(function (err) {
console.log(err);
})
)
}
and the reason for the then() returning undefined was that accidentally I had omitted return $q.when( from the second line of the this.getData function! Now I have my data in the controller just as I needed!

Post call for search data

Here i need to search name in scroll,for that i send search data query string in get call but i need to that in post.
Here is my server and client controller route and service.Also here i handling search from server side.How to post data which user has been searched ,and pass that to client and server side.
client controller service:
'use strict';
angular.module('details').factory('DetailService', ['$resource',
function($resource) {
return $resource('details', {
},
searchUsers:{
method: 'GET',
}
});
}
]);
Angular controller:
$scope.searchServer = function(searchData){
DetailService.searchUsers({search:searchData},function(response){
}, function(error){
$scope.status = 'Unable to load customer data: ' + error.message;
});
}
my Server side controller:
exports.searchCust = function (req, res) {
var strWhere = {
corporateName: search
};
db.Customer.findAll({
where: [strWhere],
}).then(function (customers) {
if (!customers) {
return res.status(400).send({
message: 'Customer not found.'
});
} else {
res.jsonp(customers);
}
})
};
my server sideroute:
app.route('/details').all(customersPolicy.isAllowed)
.get(details.searchCust);
app.param('search', details.searchCust);
};
I didn't try it out in all details as it looks like it was copy and pasted together without reading the basics. However, if you want POST requests, you need to set them both in the node-code and the Angular code, see below. What's more, Angular doesn't use JSONP, it uses JSON, so you need to set that. In the searchUsers-resource-call you only implemented the error-branch, so the results would just vanish. You'll find them in $scope.searchResults now.
client controller service:
'use strict';
angular.module('details').factory('DetailService', ['$resource',
function($resource) {
return $resource('details', {},
searchUsers: {
method: 'POST',
}
});
}]);
Angular controller:
$scope.searchServer = function(searchData) {
DetailService.searchUsers({
search: searchData
}, function(response) {
$scope.status = "OK";
$scope.searchResults = response;
}, function(error) {
$scope.status = 'Unable to load customer data: ' + error.message;
});
}
my Server side controller
exports.searchCust = function(req, res) {
var strWhere = {
corporateName: search
};
db.Customer.findAll({
where: [strWhere],
}).then(function(customers) {
if (!customers) {
return res.status(400).send({
message: 'Customer not found.'
});
} else {
res.json(customers);
}
})
};
my server sideroute:
app.route('/details').all(customersPolicy.isAllowed)
.post(details.searchCust);
app.param('search', details.searchCust);
};

angular, node + Service that returns SQL Data as json

Total newbee here. Given this service.js how can I go about returning terms data from sql server
app.service('termsService', function () {
this.getTerms = function () {
return terms
};
var terms = [
{
termid: 11, term: 'Shanika', termDefinition: 'Passmore'
}
];
});
The code below works well on its own so I want to return terms data in the service call above
var sql = require('msnodesql')
, nconf = require('nconf')
,express = require('express');
nconf.env()
.file({ file: 'config.json' });
var connectionString = nconf.get("SQL_CONN");
var app = express();
app.configure(function () {
app.use(express.bodyParser());
});
app.get("/", function(req, res) {
sql.open(connectionString, function(err, conn) {
if(err) {
}
else {
conn.queryRaw("SELECT TOP 10 termid, term, termDefinition FROM Terms", function(err, results) {
if(err) {
}
else {
res.json(results);
}
});
}
});
});
app.listen(3000);
A code for your angular service :
function Service($http) {
var Service = {};
Service.getCriteria = function (criteria,callback) {
$http({
url: "YOUR URL",
params: criteria,
method: "GET",
isArray: true
}).success(callback)
}
return Service;
}
Be aware of that is an async call, so use promises, callback or sync methods.

Resources