I have developed an Angular4 basic CRUD application that interacts with a nodejs backend API that renders data of a JSON array. But on adding an object to the JSON array using .push() method it replaces the last object with the new to be added object instead of pushing it to the array.
The following is the definition of Employee :
export interface Employee {
id:number,
name:string,
review:string[],
peers:string[]
}
The service method makes the HTTP call is following:
addEmployee(addedEmployee:Employee):Observable<Response>
{
return
this._http.post("http://localhost:3001/add",addedEmployee)
.pipe(catchError(this.handleError));
}
The backend API code that adds an Employee object to JSON object array is following:
app.post('/add',function(req,res){
var addedEmployee={};
addedEmployee.id=req.body.id;
addedEmployee.name=req.body.name;
addedEmployee.review=req.body.review;
addedEmployee.peers=req.body.peers;
employees.push(addedEmployee);
console.log('added');
res.json(employees);
})
The before, intermediate and after structures of the backend JSON object array are following:
Before:
employees = [
{
id: 1,
name: "John Doe",
review: ["Hardworking"],
peers: ["admin", "Matt"]
},
{
id: 2,
name: "Matt Hofner",
review: ["Hardworking"],
peers: ["admin"]
},
{
id: 3,
name: "Judy Ruth",
review: ["Focused"],
peers: ["admin", "Matt"]
}
];
Intermediate:
let addedEmployee:Employee = {
id: 4,
name: "Trudy",
review:["Lazy"],
peers: ["Matt"]
};
Final :
employees = [
{
id: 1,
name: "John Doe",
review: ["Hardworking"],
peers: ["admin", "Matt"]
},
{
id: 2,
name: "Matt Hofner",
review: ["Hardworking"],
peers: ["admin"]
},
{
id: 4,
name: "Trudy",
review: ["Lazy"],
peers: ["Matt"]
}
];
That's odd. This might not be the best solution but try the .concat() method :
app.post('/add',function(req,res){
var addedEmployee={};
var singleEmployeeArray = [];
addedEmployee.id=req.body.id;
addedEmployee.name=req.body.name;
addedEmployee.review=req.body.review;
addedEmployee.peers=req.body.peers;
singleEmployeeArray.push(addedEmployee);
employees.concat(singleNewEmployeeArray);
console.log('added');
res.json(employees);
})
Related
Here is my json file
{
"data": [
{
"firstName": "Tom",
"lastName": "Yoda",
"type": "guest",
"id": "0",
"gender": m,
"data": { "age": 26, "born": "UK" }
},
]
}
This data array could have more entries.
I have to map the values into an interface which looks like:
InterfacePerson {
id: string;
title: string;
firstName: string;
lastName: string;
age: string;
location: string;
}
I am unable to change the interface. So I'm trying to do some pseudo coding.
const list;
list = convertToInterfacePerson = (value): Array<InterfacePerson> => {
return {
id: value.id,
title: if(value.gender === "m")? "Mr" : "Mrs",
firstName: value.firstName,
lastName: value.lastName,
age: value.data.age,
//...
}
}
I think you were trying to use a conversion mapping function called convertToInterfacePerson but you hadn't set it up yet (separately from trying to use it). The code below shows it declared and used within a map Array method call. I believe this resolves the error(s) you were getting.
// Copied in the JSON for demonstration
const sourceJson = {
"data": [
{
"firstName": "Tom",
"lastName": "Yoda",
"type": "guest",
"id": "0",
"gender": "m",
"data": { "age": 26, "born": "UK" }
},
]
};
// Declared the InterfacePerson interface
interface InterfacePerson {
id: string;
title: string;
firstName: string;
lastName: string;
age: string;
location: string;
}
// Declared the conversion mapping function (optional parameter typing included)
const convertToInterfacePerson = (value: { firstName: string, lastName: string, type: string, id: string, gender: string, data: { age: number, born: string } }): InterfacePerson => {
return {
id: value.id,
// Removed the `if` statement due to ternary conditional
title: ((value.gender === "m") ? "Mr" : "Mrs"),
firstName: value.firstName,
lastName: value.lastName,
// Wrapped the value.data.age in a string conversion
age: String(value.data.age),
location: value.data.born
};
}
// Declared and assigned the list based on the returned array from the mapping function (each element is applied in the `convertToInterfacePerson` function)
const list = sourceJson.data.map(convertToInterfacePerson);
// Show the result of the conversion
console.log(JSON.stringify(list, null, 2));
And for a live example, check out this TypeScript Playground script containing this solution.
Brand new to react-native and typescript!
I'm have a bit of trouble extracting JSON response. I was to extract the response and put it into a class as shown below.
Here is the request code
let notifications: INotification[]
notifications = (await Requests.GET('notification/user/test-user-1', accessToken));
Here is the class
export interface INotification {
id: string;
senderId: string;
receiverId: string;
text: string;
isSeen: boolean;
type: string;
timestamp: string;
}
Here is the Postman response
{
"notifications": [
{
"pk": "user-1",
"sk": "notification1234",
"entity": "notification",
"id": "id number",
"senderId": "test-user-2",
"receiverId": "test-user-1",
"text": "Test notifications",
"isSeen": false,
"type": 2
}
]
}
Here is response from the console
{ notifications:
[ { pk: 'user#test-user-1',
sk: 'notification1234',
entity: 'notification',
id: 'id number',
senderId: 'test-user-2',
receiverId: 'test-user-1',
text: 'Test notifications',
isSeen: false,
type: 2 } ]
}
I want to be able to write out:
console.log("TEXT: ",notifications[0].text )
And get the response of : "Text: Test notifications"
Any help welcome!
the data is in an array you need to pass the array first
console.log("TEXT: ", notifications[0].text);
I have been using the ng2-smart-table template. I could not able to found the location where the data save after click the add new button.some one can help me now.
In this table create data and show in the list the data what we are created. but the case is if we are refresh the browser , the above mentioned data not saved. then what should i do for add those data for firestore.
The DataSource of the mentioned module is simply an array or LocalDataSource object according to Documentation.
Let's take an example.
On typescript file define an array like this.
data = [
{
id: 1,
name: "Leanne Graham",
username: "Bret",
email: "Sincere#april.biz"
},
{
id: 2,
name: "Ervin Howell",
username: "Antonette",
email: "Shanna#melissa.tv"
},
// ... list of items
{
id: 11,
name: "Nicholas DuBuque",
username: "Nicholas.Stanton",
email: "Rey.Padberg#rosamond.biz"
}
];
settings = {
columns: {
id: {
title: 'ID'
},
name: {
title: 'Full Name'
},
username: {
title: 'User Name'
},
email: {
title: 'Email'
}
},
add:{
confirmCreate:true
},
mode:'inline'
};
On template(html).
<ng2-smart-table (createConfirm)="addData($event)" [settings]="settings"
[source]="data"></ng2-smart-table>
Again on template.
addData(event){
//event.data is the newely created data
// Handle newly created data
// Shape of object is {
// id,
// name,
// username,
// email,
// }
// You must call event.confirm.resolve() to show data on table
}
Above addData(event) function is called when click ctrate confim.
I've currently got a local JSON file which holds the data for numerous properties. The idea is to load this JSON file into my app, and display it into a list with options to sort it (aka rearrange the data).
Here's my property.model.ts
export class Property {
ID: number;
description: string;
price: string;
agreementType: string;
streetName: string;
houseNumber: number;
postCode: string;
place: string;
image: Image[];
status: string;
constructionYear: number;
areaSize: number;
numberOfRooms: number;
numberOfBedrooms: number;
garageType: string;
garageCapacity: number;
}
export class Image {
ID: number;
base64: string;
}
This is what my json file looks like:
[
{
"ID": 1,
"description": "Lorem ipsum...",
"price": "€800,25",
"agreementType": "unknown",
"streetName": "street",
"houseNumber": 55,
"postCode": "postCode",
"place": "place",
"image": [
{
"ID": 1,
"base64": ""
},
{
"ID": 2,
"base64": ""
},
{
"ID": 3,
"base64": ""
}
],
"status": "status",
"constructionYear": 1999,
"areaSize": 50,
"numberOfRooms": 5,
"numberOfBedrooms": 2,
"garageType": "",
"garageCapacity": 0
},
{
//...
}
]
and here is my property.service.ts
export class PropertyService {
public propertyData: Observable<Property>;
constructor(private http: HttpClient) {
this.propertyData = this.observableJson();
}
observableJson() : Observable<Property> {
return this.http.get('/data/property.json')
.map((res:Response) => { res.json(); console.log(res.json())})
.catch((error:any) => Observable.throw(error.json().error || 'Server error'));
}
}
Later on, I want to be able to use my service elsewhere within the app as well, to (for instance) add a property object to it or something. Though I don't know if this is possible like that. But for now I just want to be able to somehow have my obserable array be useable in the property component. Which, at the moment, doesn't seem to work because when I use console.log(JSON.stringify(this.propertyData)); inside the constructor, I get the following error:
JS: ERROR Error: Uncaught (in promise): TypeError: Converting circular structure to JSON
JS: TypeError: Converting circular structure to JSON
now, a google search tells me that this is because it's a nested JSON object, but after many attempts I haven't been able to work out how to solve this.
Thanks in advance for any help.
The property Observable probably has something self-referential inside of it which results in the error you're seeing. You don't want to JSON.stringify propertyData which is an Observable, but you want to stringify the emitted JSON response. There are a lot of different ways to do this and it depends on the circumstances of where you are using it. For example:
this.propertyData.subscribe(data => JSON.stringify(data));
const data = JSON.stringify(await this.propertyData.toPromise());
Try this -
this.observableJson().subscribe(res => {
this.propertyData = res;
console.log(JSON.stringify(this.propertyData));
});
I will make Ajax call on my Controller action method. I want result of JSON in this format.
// array of all brands
var brands = [
{ brandId: 1, name: "Ford" },
{ brandId: 2, name: "BMW" }
];
for this i will make another call
// array of all models
var models = [
{ modelId: 1, name: "Explorer", brandId: 1},
{ modelId: 2, name: "Focus", brandId: 1},
{ modelId: 3, name: "X3", brandId: 2},
{ modelId: 4, name: "X5", brandId: 2}
];
How can i do that please guide me.
You can use following code to solve your problem
public ActionResult SomeActionMethod(int id)
{
return Json(new {foo="bar", baz="Blech"});
}
Method from the jquery getJSON method by simply...
$.getJSON("../SomeActionMethod", { id: someId },
function(data) {
alert(data.foo);
alert(data.baz);
}
);
To serialize json in your controller, may be you can use http://www.newtonsoft.com/json/help/html/serializingjson.htm