How to collect strings, sent from angularJS, in NodeRED array? - javascript

I'm trying to collect strings I send from AngularJS to a NodeRED array. The AngularJS code looks like this
this.user =
{
medName1: '',
medTime1: ''
},
{
medName2: '',
medTime2: ''
},
{
medName3: '',
medTime3: ''
};
I'm collecting form data in medName1, medTime1,.. and so on. I'm trying to send this data, over websocket, one by one to NodeRED using the following code
this.register = function() {
$scope.sock.send(this.user.medName1);
$scope.sock.send(this.user.medTime1);
$scope.sock.send(this.user.medName2);
$scope.sock.send(this.user.medTime2);
$scope.sock.send(this.user.medName3);
$scope.sock.send(this.user.medTime3);
}
register() is called when I click on "submit" button.
My question is - How do I store these strings in a nodeRED array?. Because the way I'm sending it, the string always gets stored in array index 0, overwriting the previous string. I also tried
$scope.sock.send(JSON.stringify(this.user));
but it sends the entire thing as a string to nodeRED which then makes it impossible to extract the values assigned to medName1, medTime1, and so on.
Can anyone please suggest a way!.. I'll really appreciate your help.

If you send the json.stingify version, you can then use a JSON node in your Node-RED flow to convert it back to the JavaScript object you want.

First, make your this.user an actual array:
this.user =[
{
medName1: '',
medTime1: ''
},
{
medName2: '',
medTime2: ''
},
{
medName3: '',
medTime3: ''
}];
Then, send the this.user array in a single step just as you mentioned:
this.register = function() {
$scope.sock.send(JSON.stringify(this.user));
}
Then, in NodeRED use this:
var user_array = JSON.parse( the_serialized_array );

Related

make the query dynamically to change using sanity.io groq

Hi there I'm trying to make a post request where I want to update one field on sanity.io
this is my query
patch: {
id: "f6c46b53-9313-4354-a4d6-7a40b06ee4c0",
set: {
`rewardItem[_key == \"${key}\"].lastTimeReward`: "TEst",
},
}
but this won't let me even run my project,
its giving me this error on console.log: Unexpected token;
When I do my query like this, it works
patch: {
id: "f6c46b53-9313-4354-a4d6-7a40b06ee4c0",
set: {
"rewardItem[_key == \"e88959e43ce7\"].lastTimeReward": "Test",
},
}
}]
Thanks a lot.
Your set-property is an object, and you can't enter a dynamic key directly into the object. To do what you are trying to do here, you can wrap the dynamic key in square brackets like this. That should give you the output you desire
const variable = "example"
const a = { [`template ${variable}`]: "value" }
console.log(a)

Extracting values from multiple scope inside an array

I'm building a twitter bot that takes input of someone that DM's my account, and then will output the received DM's into tweet. I'm using twit package from npm. The question is, how do you extract the id's from the output, and then use the id's in another function in order to post the tweet, using? (note that I'm currently using console.log as the tweet for now).
Input command to check the direct messages
var listMsg = T.get('direct_messages/events/list', {
count: '50'
}, function(data, response) {
console.log(response)
Output in terminal (the multiple scope inside the events array)
{
events: [
{
type: 'message_create',
id: '1275746339314216965', //take this
created_timestamp: '1592996604170',
message_create: [Object]
},
{
type: 'message_create',
id: '1274664227584671750', //and this
created_timestamp: '1592738608629',
message_create: [Object]
}
]
}
Getting the content of a direct message
var getMsg = T.get('direct_messages/events/show', {
id:'1274664227584671750' //put it to this
}, function(data, response) {
//console.log(response)
let dm = response.event.message_create.message_data
console.log(dm) //and print the message here
The content of the direct message
{
text: 'Abcd',
entities: { hashtags: [], symbols: [], user_mentions: [], urls: [] }
}
I want to get the id's as a let just like in the third code block.
You can simply use the map array function to transform the object like this
events.map( function(e) { return e.id}) or you can use es6 syntax events.map(e=> e.id)
both would return an array like this
["1275746339314216965", "1274664227584671750"]
These could be joined into into a string like so
events.map(e=> e.id).join(",")
returning
"1275746339314216965,1274664227584671750"
map() is a great function try playing around with map reduce and filter to really improve your programming. There's a great article on them here https://medium.com/poka-techblog/simplify-your-javascript-use-map-reduce-and-filter-bd02c593cc2d
Of course you could do also use a good old fashioned for loop, but think that would be a bit verbose and unnecessary (the software equivalent of making your own hammer)
e.g.
var ids = []
for(var event of events) {
ids.push(event.id)
}

AngularJS Not able to pass model data to server model appears as empty string

I'm trying to send some simple data to the server. I take the originally received server data used to create dynamic forms, quickly clean up unnecessary keys using delete formData['not_needed'], and then I wanted to add the model that has been created before posting to the server, but when I check the data objects model key that I'm trying to add it is always an empty string. I can either send one or the other, but can't seem to add one object to another as a key-value pair.
// Abridged version
var formData = $scope.responseData; // original server data to build forms
delete formData['config_data']; // remove unnecessary keys
formData.model = $scope.formModel; // add model key
$http.post('/restful/api', formData).then(function(success) {...}, function(error) {...});
The output of passed data from the server looks like:
{ id: "1", type: "type_of_form", name: "name_of_package", model: "" } // model always empty
Is this an issue using $scope?
UPDATE
Even when I hardcode the outgoing keys:
var packageData = {
"packageid": $scope.formData.id, // makes it to server
"desc": $scope.formData.desc, // also makes it to server
"data": $scope.formModel // is just an empty string
}
But formModel filled from some dumby form data when logged to console and printed out to the screen using a filter { formModel | json } looks like:
formModel = {
"document_date": "1234",
"first_name0": "1",
"first_name1": "2",
"first_name2": "3",
"first_name3": "4"
}
It could be that you're running into the by-now famous "AngularJS cannot form-URL-encode data it POSTs by default" pitfall; if so, you'll need to do this before you try and post:
.config(['$httpProvider', function ($httpProvider) {
// Intercept POST requests, convert to standard form encoding
$httpProvider.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
$httpProvider.defaults.transformRequest.unshift(function (data, headersGetter) {
var key, result = [];
for (key in data) {
if (data.hasOwnProperty(key)) {
result.push(encodeURIComponent(key) + "=" + encodeURIComponent(data[key]));
}
}
return result.join("&");
});
}]);
via How can I post data as form data instead of a request payload?

AngularJS treats POST response as string array instead of just string

I am making a POST request:
var offers = $resource('/api/offers/:id', {
id: '#id'
}
offers.save({}, { name: $scope.newOfferName }, function (offerId) {
$location.path('/offers/' + offerId);
});
I expect offerId to be a string "key", but instead I get an array [0] "k", [1] "e", [2] "y".
On the backend I use Nancy and I return the response using:
Post["/"] = _ =>
{
return Response.AsText("key");
};
The response Header say Content-Type:text/plain and in Chrome preview (Network tab) I can see "key".
When I return an object as JSON it's working fine, but I don't want to create fake class (having a string field) just to pass a string to the client.
I assume Nancy is fine here. What is happening with Angular?
You don't have to create a class for that. You can use an anonymous type:
Post["/"] = _ =>
{
return Response.AsJson(new { offerId = "key" });
};
angular has a default transform that tries to parse incoming data as json.
https://github.com/angular/angular.js/blob/master/src/ng/http.js#L94
You could remove that transform from the transformers array in $http completely, or replace it with one that checks the content-type before trying to transform the data.

Using AngularJS $filter with ng-disabled

I've got an object in my $scope that contains a bunch of details about, say, an election. This object includes a voters array of objects, each with an _id:
$scope.election = {
voters: [
{ _id: '123' },
{ _id: '456' },
{ _id: '789' }
]
}
Also in my scope I have details about the currently logged in user:
$scope.user = { _id: '456' }
How can I bind ng-disabled to the presence of $scope.user._id in the array of objects $scope.voters?
What I've Tried
I have success simply displaying the presence of $scope.user._id in $scope.election.voters like this (Jade syntax):
pre(ng-bind="election.voters | filter:{user._id} | json")
When the current user is among the voters, they get displayed. When they're not among the voters, I get an empty array. That seems quite close to what I want.
But using the same filter (sans | json) with ng-disabled, I get the Angular Infinite $digest loop error.
Is this situation too complicated? Should I move it to a $filter? If so, how would I go about making it generic enough to be useful in a number of situations (if that's even feasible)?
Can run a simple filter right in controller, or using app.filter('filterName', func...) create a custom filter you can use in markup
$scope.userIsVoter = function() {
return $scope.election.voters.filter(function(el) {
return el._id == $scope.user._id;
}).length
}
<button ng-disabled="userIsVoter()">Do Something</button>

Categories

Resources