I am getting a list by calling the $resource URL from the controller, which is viewable in the logs.
Controller
function ClubDetailController($scope, $rootScope, $stateParams, $resource,
DataUtils, entity, Club) {
var vm = this;
vm.club = entity;
vm.byteSize = DataUtils.byteSize;
vm.openFile = DataUtils.openFile;
var Todo = $resource('api/club-inchargesByClubId/:clubId');
var clubIncharges = [];
vm.clubIncharges = Todo.get({clubId: $stateParams.id}).$promise;
clubIncharges = angular.fromJson(vm.clubIncharges);
alert(clubIncharges);
})();
The problem is this list can't be stored in a var or object to be used later, for example this HTML:
<tr ng-repeat="clubIncharges in vm.clubIncharges track by clubIncharges.id">
I have also tried:
var clubIncharges = [];
clubIncharges = angular.fromJson(vm.clubIncharges);
And still couldn't get the expected output.
Updated code
var clubIncharges = [];
$http.get('api/club-
inchargesByClubId/'+$stateParams.id).then(function(response){
alert(response.data);
vm.clubIncharge = response.data;
clubIncharges = angular.fromJson(vm.clubIncharge);
vm.clubIncharges = clubIncharges;
alert(clubIncharges);
console.dir(clubIncharges);
}).catch(function(error){
console.error("Something went wrong!: " + error);
});
The list from the DB logged:
2016-10-15 13:41:22.985 DEBUG 3392 --- [nio-8081-exec-6] c.c.campuzz.aop.logging .LoggingAspect : Exit: com.campuz360.campuzz.web.rest.ClubInchargesResource.g
etClubInchargesByClubId() with result = [ClubIncharges{id=1, designaion='Chairma n', addedBy='null', clubId='2'}, ClubIncharges{id=2, designaion='bkujasrv', adde dBy='gawerg', clubId='2'}]
Latest edit
$http.get('api/club-inchargesByClubId/' + $stateParams.id).then(function (response) {
$scope.club = response.data;
}).catch(function (error) {
console.error("Something went wrong!: " + error);
});
I would do it with $http, it is cleaner to me
function ClubDetailController($scope, $rootScope, $stateParams, $http,
DataUtils, entity, Club) {
var vm = this;
vm.club = entity;
vm.byteSize = DataUtils.byteSize;
vm.openFile = DataUtils.openFile;
$http.get('api/club-inchargesByClubId/'+$stateParams.id).then(function(response){
vm.clubIncharges = response.data;
console.dir(vm.clubIncharges);
clubIncharges = angular.fromJson(vm.clubIncharges);
console.dir(clubIncharges);
}).catch(function(error){
console.error("Something went wrong!: " + error);
});
})();
EDIT
The JSON response from the OP's API has an incorrect format. I recommend to use this tool to check for a correct JSON format: https://jsonformatter.curiousconcept.com/
Todo.get({clubId: $stateParams.id}).$promise;
is returning you promise not data.
You can refer to https://docs.angularjs.org/api/ngResource/service/$resource
vm.clubIncharges = Todo.get({clubId: $stateParams.id});
Above line should work but it will not return data immediatly so your alert won't work. You can call get method like shown below to notify yourself when data is available.
vm.clubIncharges = Todo.get({clubId: $stateParams.id}, function() {
console.log(vm.clubIncharges);
});
and html should be
<tr ng-repeat="clubIncharge in clubIncharges track by clubIncharge.id">
Related
I try to create a Web App. Therefor I have to pass an Object from the backend to the HTML-Script. I tried a lot of possibilites but nothing worked.
Backend
function searchMain (allSeaVal) {
var headCon = DbSheet.getRange(1, 1, 1, DbSheet.getLastColumn()).getValues();
var bodyCon = DbSheet.getRange(valRow, typesCol, 1, DbSheet.getLastColumn()).getValues();
var Con = {
headline: headCon,
values: bodyCon
};
var tmp = HtmlService.createTemplateFromFile('page_js');
tmp.Con = Con.map(function(r){ return r; });
return tmp.evaluate();
}
HTML
<script>
function searchValues() {
var allSeaVal = {};
allSeaVal.seaType = document.getElementById('valSearchTyp').value;
allSeaVal.seaVal = document.getElementById('HSearchVal').value;
google.script.run.searchMain(allSeaVal);
Logger.log(Con);
}
<script/>
I want to use the information in "Con" in the Website. The script-code is stored in the file "page_js.
I don´t know why but I can´t pass the information into the frontend.
In your html interface you have to use the success and failure handler in your google.script.run.
Code will looks like
google.script.run
.withSuccessHandler(
function(msg) {
// Respond to success conditions here.
console.log('Execution successful.');
})
.withFailureHandler(
function(msg) {
// Respond to failure conditions here.
console.log('Execution failed: ' + msg, 'error');
})
.searchMain(allSeaVal);
Do not hesitate to check the documentation : https://developers.google.com/apps-script/guides/html/communication
Stéphane
I solved my problem with your help. Thank you so much. I struggled with this many days.
My solution is the code below.
Backend
function searchMain (allSeaVal) {
var typesCol = searchTypesCol(allSeaVal.seaType);
var valRow = searchRow(allSeaVal.seaVal, typesCol);
var headCon = DbSheet.getRange(1, 1, 1, DbSheet.getLastColumn()).getValues();
var bodyCon = DbSheet.getRange(valRow, typesCol, 1, DbSheet.getLastColumn()).getValues();
var Con = {
headline: headCon,
values: bodyCon
};
return Con;
}
HTML
function searchValues() {
var allSeaVal = {};
allSeaVal.seaType = document.getElementById('valSearchTyp').value;
allSeaVal.seaVal = document.getElementById('HSearchVal').value;
google.script.run
.withSuccessHandler(
function(Con) {
console.log(Con + 'success');
})
.withFailureHandler(
function(Con) {
console.log(Con + 'failure');
})
.searchMain(allSeaVal);
}
Good Day how can i compute a public function to route and check it on Postman? here is my codes
router.post('/post_regular_hours/:employee_id/',function(request,response,next){
var id = request.params.employee_id;
var time_in = request.params.time_in;
var time_out = request.params.time_out;
// const timein = request.params.time_in;
// const timeout = request.params.time_out;
knexDb.select('*')
.from('employee_attendance')
.where('employee_id',id)
.then(function(result){
res.send(compute_normal_hours(response,result,diff))
})
});
function compute_normal_hours(res,result,diff){
let time_in = moment(time_in);
let time_out = moment(time_out);
let diff = time_out.diff(time_in, 'hours');
return diff;
}
I want the Diff to get posted on Postman as a result
Here is the App.js of my codes. How can i call the data from mysql query to the function and return the computed data on router post
or can you guys give the right terminologies for it.
var express = require('express');
var mysql= require('mysql');
var employee = require('./routes/employee');
var time_record = require('./routes/time_record');
var admin_employee = require('./routes/admin_employee');
var tar = require('./routes/tar');
var Joi = require('joi');
var app = express();
app.get('/hello',function(req,res){
var name = "World";
var schema = {
name: Joi.string().alphanum().min(3).max(30).required()
};
var result = Joi.validate({ name : req.query.name }, schema);
if(result.error === null)
{
if(req.query.name && req.query.name != '')
{
name = req.query.name;
}
res.json({
"message" : "Hello "+name + "!"
});
}
else
{
res.json({
"message" : "Error"
});
}
});
//Database connection
app.use(function(req, res, next){
global.connection = mysql.createConnection({
host : 'locahost',
user : 'dbm_project',
password : 'dbm1234',
database : 'dbm_db'
});
connection.connect();
next();
});
app.use('/', employee);
app.use('/employee', time_record);
app.use('/admin', admin_employee);
app.use('/tar', tar);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
app.listen(8000,function(){
console.log("App started on port 8000!");
});
module.exports = app;
Here is the App.js of my codes. How can i call the data from mysql query to the function and return the computed data on router po
There are a few problems with your code.
Please see explanations in the respective code chunks.
router.post('/post_regular_hours/:employee_id/',function(request,response,next){
// If you're receiving a post request
// you'll probably want to check the body for these parameters.
let id = request.params.employee_id; // make sure the param names are matching with what you post.
// This one is special because you are passing it through the url directly
let time_in = request.body.time_in;
let time_out = request.body.time_out;
knexDb.select('*')
.from('employee_attendance')
.where('employee_id',id)
.then(function(result){
// you are not sending time_in and time_out here - but difference. but difference is not calculated.
// changed the function signature a bit - you weren't using the result at all? leaving this callback here because I'm sure you want to map the used time to some user?
return response.send(compute_normal_hours(time_in, time_out))
});
});
// this function was (and still might be) incorrect.
// You were passing res and result which neither of them you were using.
// You also had time_in and time_out which were going to be undefined in the function scope. Now that we are passing them in it should be ok. Updated it so you don't have the params you don't need.
function compute_normal_hours(time_in, time_out){
// What was diff - if it's the time difference name things correctly
// You had a diff parameter passed in (which you didn't compute), a diff function called below and another variable declaration called diff.
// you were not passing time_in or time_out parameters.
// you have moment here - are you using a library?
let time_in = moment(time_in);
let time_out = moment(time_out);
let diff = time_out.diff(time_in, 'hours');
return `Computed result is: ${diff}`;
}
Important Edit
Please search for all occurences of res.render (response.render) and replace them with something like res.send - res.render is looking for the template engine
I have just started using nodejs and koajs, and I would like to take the ip address from here: https://api.ipify.org?format=json and paste it on my site or set it as a header. Right now I have the following:
var koa = require('koa');
var app = koa();
var http = require('https');
var a = http.get("https://api.ipify.org?format=json",function(res) {
var data = "";
res.on("data", function (chunk) {
data += chunk;
});
res.on('end', function() {
par = JSON.parse(data);
console.log(par.ip);
});
});
app.listen(8888);
app.use(function *(){
this.response.set("userIp",par.ip);
this.body = "ipadress: "; //this doesn't see par.ip;
});
I know that I am probably doing something very wrong here but yea I am currently stuck because I have no idea how to take par.ip and assign it to this.body and set.
Would anyone be able to tell me how to achieve this or an alternative to the problem? Thanks in advance.
Assuming the response from api.ipify.org doesn't change.
var koa = require('koa');
var app = koa();
var http = require('https');
var a = http.get("https://api.ipify.org?format=json",function(res) {
var data = "";
res.on("data", function (chunk) {
data += chunk;
});
res.on('end', function() {
par = JSON.parse(data);
console.log(par.ip);
app.use(function *(){
this.response.set("userIp",par.ip);
this.body = "ipadress: "; //this doesn't see par.ip;
});
app.listen(8888);
});
});
Otherwise if the response from api.ipify.org constantly changes, you might to do the http request on every incoming request.
I am new to AngularJS. While trying to send formdata to Json file after click 'Add New Member' button, the new Json data overwrites the current existing Json data. I need the data to be added after the last data.
I used the code below
var memberControllers = angular.module('memberControllers', []);`memberControllers.controller('addListCtrl', ['$scope', '$http', '$location',
function($scope, $http, $location){
$scope.members = [];
$scope.formData = {};
$scope.addMember = function(){
$http.post('data/members.json', $scope.formData).
success(function(data){
console.log('added ' + data);
$scope.formData = {};
$scope.members = data;
$scope.members.push(data);
})
.error(function(data){
console.log('Error: ' + data);
});
$location.path('/members');
/*});*/
};
}]);`
The result shows from Json file --->
{"id":"1","name":"Jane" }
I expect below --->
[{"id":"1","name":"Jane"},{"id":"2","name":"John"},{"id":"3","name":"Tom"}]
$scope.members = data; overwrites members - omit this line and just use push as you're doing right after.
When I sending post request by this code:
var data = '{data: 1111}'; // = JSON.stringify(message);
console.log('NotifySplitter: ' + data);
var options = cfg.splitterOptions;
options.headers['Content-Length'] = Buffer.byteLength(data)
var req = http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log("body: " + chunk);
});
});
req.write(data);
req.end();
... and getting data by this code:
var express = require('express');
var app = express();
app.use(express.bodyParser());
app.post('/', function(request, response){
var query = request.body;
console.log(request.body);
response.end();
});
request.body contains:
{'{data: 1111}': ''}
instead expected {data: 1111}. Is it normal? How to get normal data without replacing external {} in origin data before post?
You have to set up an appropriate content-type. If you're sending json, add options.headers['Content-Type'] = 'application/json' to your request.
Also, {data: 1111} is not a JSON, it's JSON5. While it's better all around, it's not supported by default express.bodyParser(), so watch out for that.