How to update ng-repeat list after http request - javascript

I am not able to update my ng-repeat list after I do PUT request. Service works fine.
controller.js
teamData.updateTeam(team.id, teamObj, function(res) {
console.log('Success');
});
service.js
teamService.updateTeam = function(teamId, param, callback) {
var req = {
method: 'PUT',
url: '/team' + teamId,
headers: {
'Content-Type': 'application/json'
},
'data': param
};
return $http(req).then(function(res){
callback(res);
}, function(err){
callback(err);
});
};
teamRoute.js
app.put('/team/:id', function(request, response) {
var options = {
host: reqParam.hostFramework,
path: reqParam.path + '/team/' + request.params.id,
method: 'PUT',
headers: {
'token': reqParam.token,
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(JSON.stringify(request.body))
}
};
var resString = '';
var req = https.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function(d) {
resString += d;
});
res.on('end', function() {
response.send(resString);
});
});
req.write(JSON.stringify(request.body));
req.end();
});
team.html
<div ng-repeat="team in teamData">
<h2>{{team.name}}</h2>
....
</div>
My goal is to update the ng-repeat list just after PUT request is made (no page refresh). How can I achieve it?

Assign it back to the model. For example if your ng-repeat was on $scope.item then:
return $http(req).then(function(res){
callback(res);
$scope.item = res
}, function(err){
callback(err);
});

Related

Use a value from a function into another function nodejs express

I want to return the value that has been declared in the first Function CreateTag and using it as variable in the second Function CreateStream, but it won't work..
I'm working with nodejs Express.
I try to use RETURN but it won't work..
I have tried it in differance ways, but still not work..
Can you someone help me, please?
'use strict';
var express = require('express');
var router = express.Router();
/* GET home page. */
//Function 1: createTag
var createTag = function hi (TanentValue) {
var https = require('https');
var data = JSON.stringify({
name: TanentValue,
schemaPath: "Tag"
});
var options = {
hostname: 'qlik_dev.be',
path: '/meteor/qrs/tag?xrfkey=1234567890123456',
method: 'POST',
headers: {
'x-qlik-xrfkey': '1234567890123456',
'hdr-usr': 'gak\\gaka',
'Content-Type': 'application/json'
},
};
var req = https.request(options, (res) => {
//console.log(res)
res.on('data', (d) => {
console.log("hi tag")
var getResult = "GaLvAnI"; // ----> return this and use it into the function createStream
return getResult;
})
})
;
req.on('error', (error) => {
console.error(error)
});
req.write(data);
req.end();
}
//Function 2: createStream
var createStream = function (TanentValue) {
var https = require('https');
var galvani = hi(); // --------> here I made a variable to call return value
var data = JSON.stringify({
name: TanentValue,
});
var options = {
hostname: 'qlik_dev.be',
path: '/meteor/qrs/stream?xrfkey=1234567890123456',
method: 'POST',
headers: {
'x-qlik-xrfkey': '1234567890123456',
'hdr-usr': 'gak\\gaka',
'Content-Type': 'application/json'
},
};
var req = https.request(options, (res) => {
res.on('data', (d) => {
console.log(galvani); // -----> use the variable here
})
})
;
req.on('error', (error) => {
console.error(error)
});
req.write(data);
req.end();
}
//homepage
router.get('/', function (req, res) {
res.render('index', { title: 'MCS Test' });
});
//create
router.post('/create', function (req, res) {
//create tag
console.log('POST / Call Create Tag');
createTag(req.body.TanentValue);
//create stream
console.log('POST / Call Create Stream');
createStream(req.body.TanentValue);
res.send('Stream and Tag has been created');
});
module.exports = router;
you can not directly return value from async function. you have to use promise. something like this:
'use strict';
var express = require('express');
var router = express.Router();
/* GET home page. */
//Function 1: createTag
var createTag = function (TanentValue) { // function should be anonymouse
return new Promise((resolve, reject) => {
var https = require('https');
var data = JSON.stringify({
name: TanentValue,
schemaPath: "Tag"
});
var options = {
hostname: 'qlik_dev.be',
path: '/meteor/qrs/tag?xrfkey=1234567890123456',
method: 'POST',
headers: {
'x-qlik-xrfkey': '1234567890123456',
'hdr-usr': 'gak\\gaka',
'Content-Type': 'application/json'
},
};
var req = https.request(options, (res) => {
//console.log(res)
res.on('data', (d) => {
console.log("hi tag")
var getResult = "GaLvAnI"; // ----> return this and use it into the function createStream
resolve(getResult); // success call
})
})
;
req.on('error', (error) => {
reject(error); // error call
});
req.write(data);
req.end();
});
}
//Function 2: createStream
var createStream = function (TanentValue) {
createTag().then((val) => {
var https = require('https');
var galvani = val; // use that value from sucess call
var data = JSON.stringify({
name: TanentValue,
});
var options = {
hostname: 'qlik_dev.be',
path: '/meteor/qrs/stream?xrfkey=1234567890123456',
method: 'POST',
headers: {
'x-qlik-xrfkey': '1234567890123456',
'hdr-usr': 'gak\\gaka',
'Content-Type': 'application/json'
},
};
var req = https.request(options, (res) => {
res.on('data', (d) => {
console.log(galvani); // -----> use the variable here
})
})
;
req.on('error', (error) => {
console.error(error)
});
req.write(data);
req.end();
})
.catch((error) => {
// handle error from createTag function here
});
}
//homepage
router.get('/', function (req, res) {
res.render('index', { title: 'MCS Test' });
});
//create
router.post('/create', function (req, res) {
//create tag
console.log('POST / Call Create Tag');
createTag(req.body.TanentValue);
//create stream
console.log('POST / Call Create Stream');
createStream(req.body.TanentValue);
res.send('Stream and Tag has been created');
});
module.exports = router;
You can solve it using just callback function or the promise.
Using callbacks.
'use strict';
var express = require('express');
var router = express.Router();
/* GET home page. */
//Function 1: createTag
var createTag = (TanentValue, callback) => {
var https = require('https');
var data = JSON.stringify({
name: TanentValue,
schemaPath: "Tag"
});
var options = {
hostname: 'qlik_dev.be',
path: '/meteor/qrs/tag?xrfkey=1234567890123456',
method: 'POST',
headers: {
'x-qlik-xrfkey': '1234567890123456',
'hdr-usr': 'gak\\gaka',
'Content-Type': 'application/json'
},
};
var req = https.request(options, (res) => {
res.on('data', (d) => {
console.log("hi tag")
var getResult = "GaLvAnI"; // ----> return this and use it into the function createStream
callback(false, getResult);
})
});
req.on('error', (error) => {
//console.error(error)
callback(true, error);
});
req.write(data);
req.end();
}
//Function 2: createStream
var createStream = (TanentValue, callback) => {
var https = require('https');
var data = JSON.stringify({
name: TanentValue,
});
var options = {
hostname: 'qlik_dev.be',
path: '/meteor/qrs/stream?xrfkey=1234567890123456',
method: 'POST',
headers: {
'x-qlik-xrfkey': '1234567890123456',
'hdr-usr': 'gak\\gaka',
'Content-Type': 'application/json'
},
};
createTag(TanentValue, (is_error, galvani) => {
if(err || !data){
// do error handling...
callback(true); // true for there was an error
}else{
var req = https.request(options, (res) => {
res.on('data', (d) => {
callback(false);
console.log(galvani); // -----> use the variable here
})
});
req.on('error', (error) => {
callback(true);
console.error(error)
});
req.write(data);
req.end();
}
})
}
//homepage
router.get('/', function (req, res) {
res.render('index', { title: 'MCS Test' });
});
//create
router.post('/create', function (req, res) {
/*
// Since the stream seems to depend on the tag created,
// you don't need to call createTag explicitly because
// it is always/already called from createStream.
//create tag
console.log('POST / Call Create Tag');
createTag(req.body.TanentValue, function(is_error, data){
if(!is_error){
// do something
}else{
// do error handling
console.error(error);
res.send('Tag could not be created, please try later again..');
}
});
*/
//create stream
console.log('POST / Call Create Stream');
createStream(req.body.TanentValue, is_error => {
if(!is_error){
res.send('Stream and Tag has been created');
}else{
res.send('Stream could not be created, please try later again..');
}
});
});
module.exports = router;
Using Promise
'use strict';
var express = require('express');
var router = express.Router();
/* GET home page. */
//Function 1: createTag
var createTag = TanentValue => {
var https = require('https');
var data = JSON.stringify({
name: TanentValue,
schemaPath: "Tag"
});
var options = {
hostname: 'qlik_dev.be',
path: '/meteor/qrs/tag?xrfkey=1234567890123456',
method: 'POST',
headers: {
'x-qlik-xrfkey': '1234567890123456',
'hdr-usr': 'gak\\gaka',
'Content-Type': 'application/json'
},
};
return new Promise((resolve, reject) => {
var req = https.request(options, (res) => {
res.on('data', (d) => {
console.log("hi tag")
var getResult = "GaLvAnI"; // ----> return this and use it into the function createStream
resolve(getResult);
})
});
req.on('error', (error) => {
//console.error(error)
reject(error);
});
req.write(data);
req.end();
})
}
//Function 2: createStream
var createStream = TanentValue => {
var https = require('https');
var data = JSON.stringify({
name: TanentValue,
});
var options = {
hostname: 'qlik_dev.be',
path: '/meteor/qrs/stream?xrfkey=1234567890123456',
method: 'POST',
headers: {
'x-qlik-xrfkey': '1234567890123456',
'hdr-usr': 'gak\\gaka',
'Content-Type': 'application/json'
},
};
createTag(TanentValue).then( galvani => {
return new Promise((resolve, reject) => {
var req = https.request(options, (res) => {
res.on('data', (d) => {
console.log(galvani); // -----> use the variable here
resolve(d);
})
});
req.on('error', (error) => {
console.error(error)
reject({ msg: 'request error while creating the stream', error: error})
});
req.write(data);
req.end();
})
}).catch( error => {
// do error handling...
reject({msg: 'Error while creating a tag', error: error}); // true for there was an error
});
}
//homepage
router.get('/', function (req, res) {
res.render('index', { title: 'MCS Test' });
});
//create
router.post('/create', function (req, res) {
/*
// Since the stream seems to depend on the tag created,
// you don't need to call createTag explicitly because
// it is always/already called from createStream.
//create tag
console.log('POST / Call Create Tag');
createTag(req.body.TanentValue).then( data => {
// do something
}).catch( error => {
// do error handling
});
*/
//create stream
console.log('POST / Call Create Stream');
createStream(req.body.TanentValue).then( data => {
res.send('Stream and Tag has been created');
}).catch(error => {
// 'Stream could not be created, please try later again..'
res.send(error.msg);
});
});
module.exports = router;
Very handfull!! thank you it works!
But while passing the data (Json) from function 1 to function 2 with Promise, the data (json) is undefine in function 2. If I pass a data (String) from function 1 to function 2 than it works..
Why does it give me 'undefine' when it is a json?
//var id;
var req = https.request(options, (res) => {
//console.log(res)
res.setEncoding('utf8');
res.on('data', function (data) {
var json = JSON.parse(data);
var TagId = JSON.stringify(json[0]);
console.log("2 hi getTap");
console.log(TagId); // -------> here it works well
resolve(TagId);
});
});
var req = https.request(options, (res) => {
res.on('data', (d) => {
console.log("3 hi createStream");
console.log(galvani); // -------> here it doesn't work.. it gives me undefine
})
});
here a printscreen of response

Service method not getting fired using .then

Below is my AngularJs code where I am trying to call TalentPoolService.search() after succussfull ProcessCriteria call, however for some reason it not hitting the TalentPool.Service. What am I doing wrong here?
$scope.Search = function (item, SolrLabel) {
if (item != null) {
console.log('Item: ' + item.Key);
console.log('SolrLabel: ' + SolrLabel);
console.log($localStorage.message);
var pvarrData = new Array();
pvarrData[0] = JSON.stringify($localStorage.message);
pvarrData[1] = item.Key;
pvarrData[2] = SolrLabel;
$http({
method: 'POST',
url: '/api/TalentPool/ProcessCriteria',
data: JSON.stringify(pvarrData),
headers: { 'Content-Type': 'application/json' }
}).then(function (response) {
console.log('ProcessCriteria Success fired');
$localStorage.message = response.data;
console.log(response.data);
return response.data;
},
function (response) {
// failed
console.log('facet post error occured!');
}).then(
function () {
TalentPoolService.search().then(function successCallback(response1) {
$scope.talentpoolist = response1.data.model;
$localStorage.message = response1.data.baseCriteria;
console.log('TalentPoolService.search successCallback fired');
setTimeout(function () {
LetterAvatar.transform();
}, 20);
}, function errorCallback(response1) {
$scope.errors = [];
$scope.message = 'Unexpected Error while saving data!!' + response;
})
}
);
}
}
You must return data for chaining to work.
$http({
method: 'POST',
url: '/api/TalentPool/ProcessCriteria',
data: JSON.stringify(pvarrData),
headers: {
'Content-Type': 'application/json'
}
}).then(function(response) {
console.log('ProcessCriteria Success fired');
$localStorage.message = response.data;
console.log(response.data);
return response.data; // **return here**
},
function(response) {
// failed
console.log('facet post error occured!');
}).then(
function() {
TalentPoolService.search().then(function successCallback(response1) {
$scope.talentpoolist = response1.data.model;
$localStorage.message = response1.data.baseCriteria;
setTimeout(function() {
LetterAvatar.transform();
}, 20);
}, function errorCallback(response1) {
$scope.errors = [];
$scope.message = 'Unexpected Error while saving data!!' + response;
})
}
);
Why because, the next then which you are using expects some data to work on. So, if you don't return it can't. So, must return data.

How can i change the url of a http post request if there is an error

Here is the function to process my form
$scope.processForm = function () {
var url = 'http://localhost:8080/tickets/'
$http({
method: 'POST',
headers: {'Content-Type': 'application/json; charset=UTF-8'},
url: url,
data: JSON.stringify($scope.formData)
}).then(function successCallback(response) {
//log
console.log("ticket purchased");
}, function errorCallback(response) {
var requestID = JSON.stringify(response.data.requestID);
console.log("purchase failed");
});
What I would like to do is append the requestID onto the end of the url if there is an error.
If there is an error then the url should change the the below once they submit again:
var url = 'http://localhost:8080/tickets/'+ requestID
You are looking to append the requestID on the end of the url that you are submitting data to, correct?
One option would be to store either the URL or the requestID on $scope.
$scope.url = 'http://localhost:8080/tickets/';
$scope.processForm = function () {
$http({
method: 'POST',
headers: {'Content-Type': 'application/json; charset=UTF-8'},
url: $scope.url,
data: JSON.stringify($scope.formData)
}).then(function successCallback(response) {
//log
console.log("ticket purchased");
}, function errorCallback(response) {
var requestID = JSON.stringify(response.data.requestID);
$scope.url = 'http://localhost:8080/tickets/' + requestID;
console.log("purchase failed");
});
I figured out how to achieve what I wanted in the end. I saved the url and the requestID on $scope.
if ($scope.requestID == null) {
$scope.url = 'http://localhost:8080/tickets/';
}
else if ($scope.requestID !== null && $scope.firstTransaction == null) {
$scope.firstRequest = $scope.requestID;
console.log("first transaction id = " + $scope.requestID)
$scope.url = 'http://localhost:8080/tickets/' + $scope.firstRequest;
}
$scope.processForm = function() {
$http({
method: 'POST',
headers: {
'Content-Type': 'application/json; charset=UTF-8'
},
url: $scope.url,
data: JSON.stringify($scope.formData)
}).then(function successCallback(response) {
//log
console.log("ticket purchased");
}, function errorCallback(response) {
var requestID = JSON.stringify(response.data.requestID);
$scope.url = 'http://localhost:8080/tickets/' + requestID;
console.log("purchase failed");
});

Binding a service response in Angular JS

I am trying to send the http response as a JSON body to an error handler if an error occurs. I am not really sure how to do this as I am a little inexperienced in this area. Here is the relevant code that I have currently:
Controller:
for (var prop in $scope.applicants) {
var applicant = $scope.applicants[prop];
$scope.sendApplicantsToSR(applicant).then(null, $scope.sendATSError.bind(null, applicant));
}
$scope.sendATSError = function (applicant, error) {
return AtsintegrationsService.applicantErrorHandling(applicant.dataset.atsApplicantID);
};
$scope.sendApplicantsToSR = function(applicant) {
return AtsintegrationsService.sendApplicantsToSR(applicant);
};
Service:
srvc.sendApplicantsToSR = function (applicant) {
var applicantURL = {snip};
return $http({
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
method: 'POST',
url: applicantURL,
data: applicant
});
};
srvc.applicantErrorHandling = function (applicantID, error) {
var url = srvc.url + {snip};
return $http({
method: 'POST',
url: url,
data: { "error_message": error }
});
};
So, ideally, I would like to pass the result of $scope.sendApplicantsToSR to $scope.sendATSError only when an error occurs.
Inside your controller
YourService.getdatafromservice().then(function(SDetails) {
//response from service
console.log(SDetails);
});
Inside your service
return {
getData: getData
};
function getData() {
var req = $http.post('get_school_data.php', {
id: 'id_value',
});
return req.then(handleSuccess, handleError);
function handleSuccess(response) {
response_data = response.data;
return response_data;
}
function handleError(response) {
console.log("Request Err: ");
}
}

Create GitHub repo from node.js

I have this function in my node project, that should create a new GitHub repository for a specific user:
exports.create_repo = function (repo) {
var options = {
host: "api.github.com",
path: "/user/repos?access_token=" + repo.accessToken,
method: "POST",
json: { name: repo.name },
headers: { "User-Agent": "github-app" }
};
var request = https.request(options, function(response){
var body = '';
response.on("data", function(chunk){ body+=chunk.toString("utf8"); });
response.on("end", function(){
var json = JSON.parse(body);
console.log(json);
});
});
request.end();
}
Every time I use it, the response is:
{ message: 'Not Found',
documentation_url: 'https://developer.github.com/v3' }
What do I do wrong ?

Categories

Resources