JSON new data push. How to save changes? With AngularJs - javascript

all. I'm new with Angular. I need to find out how to save my JSON changes after push.
app.controller('ReviewController', function(){
this.r = {};
this.addReview = function(product){
this.r.createdOn = Date.now();
product.reviews.push(this.r);
this.r = {};
};
});
also I have this thing, where I get JSON data. I don't know if it would be useful for you to know that
app.factory('events', function($http) {
return function(){
return $http.get('products.json');
};
});
app.controller("StoreController", function(events){
var store = this;
store.products = [];
events().success(function(data) {
store.products = data;
});
One more thing. My products.json file:
[
{
"title": "Rubinas",
"price": 199.99,
"description": "Labai kietas, davai pirkit.",
"images": {
"full": "images/gem2.gif",
"thumb": "images/gem2t.gif"
},
"reviews": [
{
"stars": 1,
"body": "Bullshit",
"author": "Hater",
"createdOn": 1397490980837
},
{
"stars": 3,
"body": "Simple stone!",
"author": "Dude",
"createdOn": 1397490980837
},
{
"stars": 5,
"body": "Amazing.",
"author": "Kate",
"createdOn": 1397490980837
}
],
"canPurchase": true,
"soldOut": false
},
{
"title": "Smaragdas",
"price": 499.99,
"description": "Oho, koks.",
"images": {
"full": "images/gem3.gif",
"thumb": "images/gem3t.gif"
},
"reviews": [
{
"stars": 5,
"body": "This is so amazing",
"author": "Steeler",
"createdOn": 1397490980837
},
{
"stars": 4,
"body": "Pretty cool!",
"author": "Jim",
"createdOn": 1397490980837
},
{
"stars": 2,
"body": "I don't like it very much.",
"author": "Kim",
"createdOn": 1397490980837
}
],
"canPurchase": true,
"soldOut": false
},
{
"title": "Deimantas",
"price": 9999.99,
"description": "Labai kietas, na bet rimtai.",
"images": {
"full": "images/gem4.gif",
"thumb": "images/gem4t.gif"
},
"reviews": [
{
"stars": 1,
"body": "Eww...",
"author": "Hater",
"createdOn": 1397490980837
},
{
"stars": 4,
"body": "Nice!",
"author": "Dude",
"createdOn": 1397490980837
},
{
"stars": 5,
"body": "So unbelievible.",
"author": "Matt",
"createdOn": 1397490980837
},
{
"stars": 2,
"body": "I don't like it.",
"author": "Steven",
"createdOn": 1397490980837
}
],
"canPurchase": true,
"soldOut": false
}
]

The are some ways to do this
First : You can create a button say called "save changes", and tell the user after finishing the process of adding new data with your so-called function addReview, Hit the save changes , and in the on-click of this button , you can create a $http.post request and send your new pushed array into your database (or your json file , whatever it is)
Second : You can do the same $http.post in your own function , addReview, without creating a button and listening for user to click on save changes button.
For example:
if you want to go for my second solution :
this.addReview = function(product){
this.r.createdOn = Date.now();
product.reviews.push(product);
this.r = {};
$http.post('yourServerFile',WhateverYouWantToSave)
.success(function(){
alert('Your Changes have been saved to database');
})
};
//Dont forget to inject $http into your controller
And its better to define a factory/servise for this kind of theories(pushing/adding/sending/deleting somethig from somewhere)

Related

Error querying by string in nodejs api rest

I'm actually creating an app for my neighborhood little business, y have this db schema using Postgresql:
https://res.cloudinary.com/dthhugesg/image/upload/v1569939688/nodejserror/lugarlov_schema_db_dykxnt.png
my use cases are:
1 user can create 1 experience.
1 user can create a business local only if its going to leave an experience from it.
1 experience can have several images.
( I haven't a relationship between business_locals and users because doesn't matter for who creates the business).
I haven't had problems untill now, I'm trying to get the business with it's name, lat and lng; the average score given by users, 1 image from the last experience where the name like = "somestring"
this are my models:
Business Model: https://res.cloudinary.com/dthhugesg/image/upload/v1569939688/nodejserror/lugarlov_businessmd_rwnsnu.png
Images model: https://res.cloudinary.com/dthhugesg/image/upload/v1569939688/nodejserror/lugarlov_imgaesmd_m4hkzv.png
experiencies model: https://res.cloudinary.com/dthhugesg/image/upload/v1569939688/nodejserror/lugarlov_experienciesmd_f7jtxt.png
y try this code:
export async function getBusinessByQueryString(req, res) {
let query = req.params.query;
const businessesResult = await Business.findAll({
where: Sequelize.where(
Sequelize.fn("LOWER", Sequelize.col("name")),
{
[Op.like]: `%${query}%`
}
),
attributes: ['name', sequelize.fn('COUNT', sequelize.col('experiencies.id'))],
include: [
{ model: Experiencies, attributes: [] }
],
group: ["business_locals.id"]
}).catch(err => {
return res.status(500).json({
ok: false,
messagge: "Error al consultar el comercio",
err
});
});
console.log(businessesResult);
// let businessIdArrays = businessesResult.map((obj) => obj.id);
// console.log(businessIdArrays);
return res.json({
ok: true,
message: businessesResult
});
}
but I'm having this error:
https://res.cloudinary.com/dthhugesg/image/upload/v1569939691/nodejserror/error_x0tsiq.png
I'm expecting this:
[
{
"id": 2,
"name": "Business local example 1",
"lat": 6.24523,
"lng": -75.4543,
"average_score": 4,
"experiences": [
{
"id": 1,
"comment": "was a good experience to be there, good food and cool service",
"score_given": 4,
"created_at": "2019-09-30 18:55:00",
"images": [
{
"url": "https://placeimg.com/640/490/tech"
},
{
"url": "https://placeimg.com/640/490/animals"
}
],
"user": {
"name": "Esteban nuevo nombre",
"phone": "0000000+"
}
},
{
"id": 1,
"comment": "was a good experience to be there, good food and cool service",
"score_given": 4,
"created_at": "2019-09-30 18:55:00",
"images": [
{
"url": "https://placeimg.com/640/490/tech"
},
{
"url": "https://placeimg.com/640/490/animals"
}
],
"user": {
"id": 2,
"name": "Esteban nuevo nombre",
"phone": "0000000+"
}
},
{
"id": 2,
"comment": "was a good experience to be there, good food and cool service",
"score_given": 4,
"created_at": "2019-09-30 18:55:00",
"images": [],
"user": {
"name": "Esteban nuevo nombre",
"phone": "0000000+"
}
},
{
"id": 3,
"comment": "was a good experience to be there, good food and cool service",
"score_given": 4,
"created_at": "2019-09-30 18:55:00",
"images": [],
"user": {
"name": "Esteban nuevo nombre",
"phone": "0000000+"
}
},
{
"id": 4,
"comment": "was a good experience to be there, good food and cool service",
"score_given": 4,
"created_at": "2019-09-30 18:55:00",
"images": [],
"user": {
"name": "Esteban nuevo nombre",
"phone": "0000000+"
}
}
]
},
{
"id": 3,
"name": "Business local example 2",
"lat": 6.24523,
"lng": -75.4543,
"average_score": 4,
"experiences": [
{
"id": 1,
"comment": "was a good experience to be there, good food and cool service",
"score_given": 4,
"created_at": "2019-09-30 18:55:00",
"images": [
{
"url": "https://placeimg.com/640/490/animals"
}
],
"user": {
"id": 2,
"name": "Esteban nuevo nombre",
"phone": "0000000+"
}
},
{
"id": 4,
"comment": "was a good experience to be there, good food and cool service",
"score_given": 4,
"created_at": "2019-09-30 18:55:00",
"images": [],
"user": {
"name": "Esteban nuevo nombre",
"phone": "0000000+"
}
}
]
}
]
thank you very much, all of you i hope that someone can help me and tell me if i have any mistake

Postman - How to count occurrences of a specific object in a JSON response

I am new to JSON and Postman. I believe I'm trying to do something very simple.
I have created a GET request which will get a JSON response like the one below.
In the example below I want to get the count of All "IsArchived" attributes in the response;
The number of those attributes will vary from response to response.
How can I do it? Thanks in advance
{
"Id": 1328,
"Name": "AAA Test",
"Owner": {
"Id": 208,
"Name": "The Boss"
},
"FieldGroups": [
{
"Id": "c81376f0-6ac3-4028-8d61-76a0f815dbf8",
"Name": "General",
"FieldDefinitions": [
{
"Id": 1,
"DisplayName": "Product Name",
"IsArchived": false
},
{
"Id": 2,
"DisplayName": "Short Description",
"IsArchived": false
},
{
"Id": 33,
"DisplayName": "Long Description",
"IsArchived": false
},
]
},
{
"Id": "5ed8746b-0fa8-4022-8216-ad3af17db91f",
"Name": "Somethingelse",
"FieldDefinitions": [
{
"Id": 123,
"DisplayName": "Attribution",
"IsArchived": false
},
{
"Id": 1584,
"DisplayName": "FC1",
"IsArchived": false
},
{
"Id": 623,
"DisplayName": "Sizes",
"IsArchived": false,
"Owner": {
"Id": 208,
"Name": "The Boss"
},
"Unit": "",
"Options": [
{
"Id": 1,
"Value": "XS"
},
{
"Id": 2,
"Value": "S"
},
{
"Id": 3,
"Value": "M"
}
]
}
]
}
],
"IsArchived": false
"Version": 1
}
It is a rather specific solution but I hope it helps. The description is added as comments:
// Convert the response body to a JSON object
var jsonData = pm.response.json()
// Create a count variable which will be increased by 1 everytime IsArchived occurs
var count = 0;
function countIsArchived() {
// Loop through the FieldGroupsArray
_.each(jsonData.FieldGroups, (fieldGroupsArray) => {
// Loop through the FieldDefinitionsArray
_.each(fieldGroupsArray.FieldDefinitions, (fieldDefinitionsArray) => {
// Check if IsArchived exists
if(fieldDefinitionsArray.IsArchived) {
// Increase count by 1
count++;
}
});
});
// IF you want it:
// Check if IsArchived exists on the top level of the JSON response and increase count
if(jsonData.IsArchived) {
count++;
}
// IF you want it:
// Create a Postman environment variable and assign the value of count to it
pm.environment.set("count", count);
}
Additional info:
The , after the following object is not needed. It invalidates the JSON:
{
"Id": 33,
"DisplayName": "Long Description",
"IsArchived": false
}, <--

Adding object properties from one JSON data file to another

I have two local JSON files. I want to add the property of one object from one file to the corresponding object in the other file.
Here is an example..
Array1:
[
{
"id": 1,
"username": "Joe Smith",
"pic": "images/profile/Joe_smith.jpg"
},
{
"id": 2,
"username": "Jane Smith",
"pic": "images/profile/Jane_smith.jpg"
}
]
Array2:
[
{
"id": 3,
"userId": 1,
"profession": "dentist"
},
{
"id": 4,
"userId": 2,
"profession": "pilot"
}
The idea is to add the "pic" property from Array1 to the correct object in Array2. If the id from Array1 matches the userId from Array2, it's a correct match. Array2 would end up looking like this:
[
{
"id": 3,
"userId": 1,
"profession": "dentist",
"pic": "images/profile/Joe_smith.jpg"
},
{
"id": 4,
"userId": 2,
"profession": "pilot",
"pic": "images/profile/Jane_smith.jpg"
}
Afterwards I'm going to use angular to display a name with the face. Hope I explained that ok. Any help would be much appreciated!
Just for the fun of it. In this example using https://lodash.com.
var people = [
{ "id": 1, "username": "Joe Smith", "pic": "images/profile/Joe_smith.jpg" },
{ "id": 2, "username": "Jane Smith", "pic": "images/profile/Jane_smith.jpg"},
{ "id": 3, "username": "I play too much games", "pic": "images/profile/toomuch.jpg"}
];
var professions = [
{ "id": 3, "userId": 1, "profession": "dentist" },
{ "id": 4, "userId": 2, "profession": "pilot" }
];
var workers = _.map(people, function(human) {
var work = _.findWhere(professions, { 'userId': human.id });
return _.extend(human, work ? work : { 'profession' : 'unemployed' });
});
console.log(workers);

JSon Parsing not working

I am trying to parse JSON data from the flixter API to import it to my blog.
In the example below, I tried using JavaScript to output the cast info for the movie expendables.
My full goal would be to get it to output the information
"Sylvester Stallone as Barney Ross, Jason Statham as Lee Christmas" and so on.
Here is my jsFiddle http://jsfiddle.net/k3V9p/3/
var jsontext = '{
"cast": [{
"id": "162664630",
"name": "Sylvester Stallone",
"characters": ["Barney Ross"]
}, {
"id": "162653720",
"name": "Jason Statham",
"characters": ["Lee Christmas"]
}, {
"id": "162652223",
"name": "Jet Li",
"characters": ["Yin Yang"]
}, {
"id": "162664307",
"name": "Dolph Lundgren",
"characters": ["Gunnar Jensen"]
}, {
"id": "162670654",
"name": "Chuck Norris",
"characters": ["Booker"]
}, {
"id": "326392465",
"name": "Terry Crews",
"characters": ["Hale Caesar"]
}, {
"id": "770731413",
"name": "Randy Couture",
"characters": ["Toll Road"]
}, {
"id": "770833479",
"name": "Liam Hemsworth",
"characters": ["Billy the Kid"]
}, {
"id": "770704326",
"name": "Scott Adkins",
"characters": ["Hector"]
}, {
"id": "770670020",
"name": "Nan Yu",
"characters": ["Maggie"]
}, {
"id": "162670708",
"name": "Jean-Claude Van Damme",
"characters": ["Jean Vilain"]
}, {
"id": "162652509",
"name": "Bruce Willis",
"characters": ["Mr. Church"]
}, {
"id": "162662233",
"name": "Arnold Schwarzenegger",
"characters": ["Trench"]
}, {
"id": "489251774",
"name": "Amanda Ooms",
"characters": ["Pilar"]
}, {
"id": "377608335",
"name": "Charisma Carpenter",
"characters": ["Lacy"]
}, {
"id": "771417014",
"name": "Nikolette Noel",
"characters": ["Sophia"]
}],
"links": {
"rel": "http://api.rottentomatoes.com/api/public/v1.0/movies/771238417.json"
}
}';
var titles = JSON.parse(jsontext);
document.write(titles.cast);
The problem you have is with end of lines in your string literal. You can write them like this :
var jsontext = '{\
"cast": [{\
But in your case, it's not clear if you really need JSON, as you could directly create your object as
var titles = {
cast": [{
...
I would say that the first problem you have is the JSON.parsing (which dystroy has perfectly answered), after solving that you will have to deal with rendering which you could do like this: (demo)
var titles = {
"cast": [{
"id": "162664630", "name": "Sylvester Stallone", "characters": ["Barney Ross"]
}, {"id": "162653720", "name": "Jason Statham", "characters": ["Lee Christmas"]
}, {"id": "162652223", "name": "Jet Li", "characters": ["Yin Yang"]
}, {"id": "162664307", "name": "Dolph Lundgren", "characters": ["Gunnar Jensen"]
}, {"id": "162670654", "name": "Chuck Norris", "characters": ["Booker"]
}, {"id": "326392465", "name": "Terry Crews", "characters": ["Hale Caesar"]
}, {"id": "770731413", "name": "Randy Couture", "characters": ["Toll Road"]
}, {"id": "770833479", "name": "Liam Hemsworth", "characters": ["Billy the Kid"]
}, {"id": "770704326", "name": "Scott Adkins", "characters": ["Hector"]
}, {"id": "770670020", "name": "Nan Yu", "characters": ["Maggie"]
}, {"id": "162670708", "name": "Jean-Claude Van Damme", "characters": ["Jean Vilain"]
}, {"id": "162652509", "name": "Bruce Willis", "characters": ["Mr. Church"]
}, {"id": "162662233", "name": "Arnold Schwarzenegger", "characters": ["Trench"]
}, {"id": "489251774", "name": "Amanda Ooms", "characters": ["Pilar"]
}, {"id": "377608335", "name": "Charisma Carpenter", "characters": ["Lacy"]
}, {"id": "771417014", "name": "Nikolette Noel", "characters": ["Sophia"]
}],
"links": {
"rel": "http://api.rottentomatoes.com/api/public/v1.0/movies/771238417.json"
}
},
star,
staring = [];
for (star = 0; star < titles.cast.length; star++) {
staring.push(titles.cast[star].name + ' as ' + titles.cast[star].characters[0]);
}
document.getElementById('Credits').innerHTML = staring.join(', ');
You don't need to change what flixster api is returning to you.
The problem is you need to call the API directly... do not copy&paste the result.
See the usage here http://developer.rottentomatoes.com/docs/read/json/v10/examples
Just do the Ajax call and onSuccess (searchCallback in the example) you will have the data parsed in json already.

Getting Messages from Inbox

I have a question about the Graph API.
I use Javascript for the API and make a little test website ,where you can log in ,look for new messages and write a new status.
My problem is that I can't get the messages or the thread.
FB.api('/me/inbox',function(response) { alert(response.id); } ); don't work.
Have somebody an example for getting the messages in the inbox??
Thanks
The /me/inbox request requires that you have the read_mailbox permission granted.
Once you've got that, the /me/inbox request will return an array of Thread's, which will look something like this;
{
"data": [
{
"id": "1126884978255",
"from": {
"name": "Someone's Name",
"id": "34723472"
},
"to": {
"data": [
{
"name": "Someone's Name",
"id": "34723472"
},
{
"name": "Matt Lunn",
"id": "560914724"
}
]
},
"message": "Testing the one-ness.",
"updated_time": "2012-01-31T12:13:00+0000",
"unread": 0,
"unseen": 0,
"comments": {
"data": [
{
"id": "1126884978255_6769",
"from": {
"name": "Someone's Name",
"id": "34723472"
},
"message": "£140!?",
"created_time": "2012-01-31T11:33:15+0000"
},
{
"id": "1126884978255_6771",
"from": {
"name": "Matt Lunn",
"id": "560914724"
},
"message": "^^ month in advance as well",
"created_time": "2012-01-31T11:33:26+0000"
}
]
},
"type": "thread"
}
],
"summary": {
"unseen_count": 0,
"unread_count": 21,
"updated_time": "2012-01-31T13:19:31+0000"
}
}
So depending which ID you're after, you'll have to do;
for (var i=0;i<response.data.length;i++) {
var thread = response.data[i];
for (var j=0;j<thread.comments.data.length;j++) {
var comment = thread.comments.data[j];
console.log(comment.message);
}
}
Hopefully you get the idea...

Categories

Resources