Issue with saving form values in Angular - javascript

I am trying to save values of two different forms in a single array and have to send them to a server using POST. Right now, I have hardcoded an array into my services.ts and I am trying to push values of an array from my .ts into that array. The problem is that when I save the form the data from that one particular form is forwarded to the array in services. I tried using the save method in submit of both the forms but That just creates 2 objects, whereas, I need One object with the other one nested inside of it. Here is the class I am using :
export interface Mod {
id : number ,
name? : string,
clauseList? : Clause
country? : string;
company? : string;
process? : string;
}
export interface Clause {
cName? : string,
cid? : number,
desc? :string,
// pc : number,
parentC? :number,
id? : number,
text? : Text
}
export interface Text {
txt? : string,
tid? : number
}
Here is the Stackblitz I cannot figure out the issue here, but in my local machine when I save the form a new object is created and displayed in the console.
Here is what I get in the console demoImage The object at [0] is the one I hardcoded and is the format I need the data in, the object at [1] is what I get on saving the forms.
Can anyone assist me with how to create a new object with the required elements in it?
Please read the readme.txt in the Stackblitz demo to get a better understanding of what I need help with

In the addFilter(...) you may simply do:
addFilter(filter: NgForm) {
this.mergedObj['filterKey'] = filter.value;
filter.reset();
console.log("filterAdded : : ", this.mergedObj)
}
Thereby, we define a key (which can be any string) to hold a value that is the current filter.value object.

Related

How do I check if an object is within an array in Javascript?

I am getting stuck on a project where I am trying to pull out relevant data from a super massive Google Maps Timeline json, and running into the problem of the structure not being as orderly as I thought it was. Essentially, I am trying to pull out an address, time, date and mileage out of this json for every trip in my car. to use this data, I pasted it into a normal javascript file and named it so I can use it as an object. I then take this data and create a string that will format that info like a CSV file.
From going over the structure of the json by looking at only a few trips, I was able to determine the following general structure:
const google = {
timelineObjects: [
0: {activitySegment: {A NUMBER OF OBJECTS}},
1: {placeVisit : {A NUMBER OF OBJECTS}},
2: {activitySegment: {A NUMBER OF OBJECTS}},
3: {placeVisit : {A NUMBER OF OBJECTS}}
]
}
activitySegment has all the travelling info, like distance, travel times, etc. placeVisit has info about the destination. In my small sample, I was able to just loop through each using an if statement with i%2=0, and just change what I wanted to pull out from each, which worked well.
When I tried adding a larger sample, I was finding that Google occasionally did not create a activitySegment object and only had a placeVisit, which was throwing "Uncaught TypeError: Cannot read property 'distance' of undefined".
I am sure that the even/odd sorting will not work out any more. Is there a way to use a conditional to show if google[timelineObjects][i] is either a {activitySegment} or {placeVisit}? Or, is there a better way to figuring out what object is next in the array?
You can test to see if the Object at the particular array index has a given property using Object.prototype.hasOwnProperty():
const google = {
timelineObjects: [
{activitySegment: {}},
{placeVisit : {}},
{activitySegment: {}},
{placeVisit : {}}
]
};
console.log(google.timelineObjects[0].hasOwnProperty("activitySegment")); // true
console.log(google.timelineObjects[1].hasOwnProperty("activitySegment")); // false
If your objective to see what type of object you get. You can iterate over each object, see what the key of the object is and process the data depending on the key value. Something like this.
Object.entries(google).forEach(([key, value]) => {
if(key==='activitySegment') {
//process activeSegment here
}else {
//process placeVisit here
}
})

How to prevent the sequelize from creating the output clause

When I do a create using sequelize it returns me the response i.e. the newly created entry row in the response,
Sequelize Create Object Code:
let createdObj= await sequelize.ModelName.create(modelObject,{ transaction :t, //more options can be added here, need some value of option that prevents the output inserted })
Below is the query created:
INSERT INTO [TABLE_NAME] ([COL1],[COL2],[COL3],[COL4]) OUTPUT INSERTED.* VALUES (#0,#1,#2,#3,#4)
Now I don't want the output clause to be part of the query, I want a simple insert like:
INSERT INTO [TABLE_NAME] ([COL1],[COL2],[COL3],[COL4]) VALUES (#0,#1,#2,#3,#4)
I don't want the output clause to be part of the query.
How can I achieve this in at the query level as well as at the model level? In some Create operations, I want the output clause and in some create operations, I don't want.
EDIT 1
On Further research I found an option called { returning: false } this does what is required i.e. create an insert query like this INSERT INTO [TABLE_NAME] ([COL1],[COL2],[COL3],[COL4]) VALUES (#0,#1,#2,#3,#4) but now the Sequelize is breaking because it's expecting those values back in return idk why?
C:\Users\MG265X1\project\node_modules\sequelize\lib\dialects\mssql\query.js:389
id = id || results && results[0][this.getInsertIdField()];
^
TypeError: Cannot read property 'id' of undefined
at Query.handleInsertQuery (C:\Users\MG265X1\project\node_modules\sequelize\lib\dialects\mssql\query.js:389:39)
Turns out if an autoIncrementAttribute is present in the model, it will look for the output clause, removing the attribute {autoIncrement: true } from the model hasn't helped as IDENTITY_INSERT cannot be null. How do I move ahead on this??
Edit 2 I could get it working with a combination of { returning: false } and {hasTriggers: true}. Have hasTriggers Attribute as true in your Model, this will allow you to single creates but for bulk Creates pass option returning: false at the time of bulkCreate.
Note: When using bulkCreate with { returning: false } you'll not be able to get the autogenerated Id, It's a trade-off that we had to live with as we want
bulkCreate to work with triggers, we ended up fetching the Id later from DB
Seems I raised this issue but was closed as it wasn't good SSCCE

JavaScript problem converting strings inside object (inside loop)

While building a carousel module for Joomla I am having 2 JavaScript issues I can't get fixed. I've been trying for 2 days. Hopefully someone here can point out what I am doing wrong.
I can't get a boolean from a string "0" or string "1"
And I can't JSON.parse() to convert an object string to a JavaScript object
The situation:
To be able to have multiple instances on 1 page I am passing each modules individual settings (via php) to 1 object in my javascript file. Each module is 1 key value pair inside the object, the value being its own settings object. Basicly, this is how the JS recieves it:
const moduleSettings = {
"103":{"items":3,"margin":5,"loop":"1","center":"0","responsive":"{0:{items:1}}"},
"105":{"items":3,"margin":5,"loop":"0","center":"1","responsive":"{0:{items:2}}"}
};
Next I need to loop over each module to initialize the settings. This is done on ready using jQuery.
jQuery(document).ready(function() {
// Loop over each module
const modules = Object.keys(moduleSettings);
for (const id of modules) {
const target = "carousel-" + id;
const params = moduleSettings[id];
// Callback to evaluate true/false params
function eval(singleParam) {
return params[singleParam] === "1";
};
// Initialize carousel
jQuery(target).owlCarousel({
items: params.items,
margin: params.margin,
loop: eval("loop"),
center: eval("center"),
responsive: JSON.parse(params.responsive)
});
};
});
The carousel properties items & margin are numbers. No problem there, but these are recieved as numbers from the start.
The problem:
The properties loop & center should return a boolean, based on the callback function eval(). But they just return the string "0" or "1".
The property responsive should return an object. But this still remains a string object "{...}".
The console error:
The first problem above does not block functionallity. It works, but I want to understand why my values are not booleans.
The second problem however causes console error and make the carousel not work. This is only IF responsive is not an empty string. When responsive is an empty string, it works. But I need the responsive setting.
I've been looking for the cause of this issue for 2 days now. It's getting frustrating. Any pointers would be most helpfull. Thanks!
instead of using eval function use can you below
jQuery(target).owlCarousel({
items: params.items,
margin: params.margin,
loop: !!params.loop,
center: !!params.center,
responsive: JSON.parse(params.responsive)
});
For the second issue, you need to change the structure from your server side code to generate this module settings JSON. The responsive object is not a proper JSON. its should be like
responsive: {items:1} or responsive: [{items:1}]
If you can post that code then I can tell you the change need to made there.
In the example you've provided, you're not evaluating the params field by name provided as a singleParam argument, but the actual params.singleParam field, which is undefined. To fetch field by it's name use brackets syntax: params[singleParam].

Mongodb E11000 duplicate key error on array field

I have a quick question about mongoose schema real quick. Here is the code: https://i.ibb.co/Db8xPMw/5555.png
I tried to create a document without the property "work". It works in the first time, but it didn't start to work on the second time that I do the same thing again.
Do you have any idea?
Basically I create two documents without an "work" property, which causes a duplicate key error. However, I didn't set up unqiue: true though.
Error :
"errmsg" : "E11000 duplicate key error collection: test.user index work_1 dup key: { : null }
From the message it says your collection has an index with name work_1 probably on field work, Since you've created a document without work field then basically you cannot create another document without work field what so ever in the same collection, cause two documents with no work field or even work field with value as null or same cannot exist as it violates unique constraint policies (it says dup key : { : null}) !! Uniques indexes can be created via mongoose schemas or can also be created by manually running queries on database.
Ref : Search for Unique Index and Missing Field in index-unique
So you need to drop the existing index using dropIndex & then if needed recreate it using createIndex. MongoDB would automatically convert a created index to index-multikey (multi-key index - indexes on array fields) if at least one existing document has array value for that indexed field by the time you create index or even if an array value gets inserted for that field in future.
Through code - Drop index : yourSchema.dropIndex({yourFieldName: 1}) && Create index : yourSchema.index({yourFieldName : 1})
NOTE : Just in case if you want to have certain criteria in unique indexes like situation from this question where indexed field can be missing in some documents but it shouldn't be considered as duplicate insertion, then you can take use of partial-indexes (Search for Partial Index with Unique Constraint) which would only index documents where work field exists.
Ex of partial-indexes :-
db.yourCollectionName.createIndex(
{ work: 1 },
{ unique: true, partialFilterExpression: { work: { $exists: true } } }
)
Ref : mongoose-Indexes

passing different arrays parameters in pact

I have two api calls , with the only difference being in the array parameters :
// it is used for displaying whole list
Query 1 : limit=25&var1=[deleted=false]
//it is used for displaying on basis of id
Query 2 : limit=25&var1=[deleted=false,id=10005]
I tried using term , also something like but it takes both the query as one
var1: term({
generate: '[deleted=false]',
matcher: '[deleted=false]'}),
var1: term({
generate:'[deleted=false,id=10005]',
matcher:'[deleted=false,id=10005]'}),
Also , i passed the exact query but it doesn't work
Any suggestions on how to do it ?
If you want to using dynamic legnth array type by parameter in javascript, Use this.
var [deleted, id, ...any] = parameter;
console.log(deleted, id);
In case, if you throw parameter([deleted]), log be printed by "deleted, id is undefined".

Categories