Angular reading data from json into textarea - json

I'm trying to read some test data from a local json file and output the data with correct formatting into a textarea. Right now though it just outputs [object Object]. How would I go about getting it so it outputs:
Id: theIdGoesHere
Title: theTitleGoesHere
step.service.ts The service used to call the json data
public getJson(): Observable<any>{
return this.http.get('/assets/jsonData/MyJson.json')
.map(response => response.json());
}
MyJson.json
{
"data":[
{
"id": 1,
"title":"Test1"
},
{
"id": 2,
"title":"Test2"
}
]
}
main.componenet.ts
private testVar: any;
test(){
this.stepService.getJson().subscribe(data => (this.testVar = data));
}
anothermethod(){
this.test();
this.mainStepText = this.testVar; //mainStepText binded to textarea with [(ngModel)]="mainStepText"
}
get mainStepText2() { //Rebinded this one
const text = [];
const { data } = this.testVar;
for (let item of this.testVar.data) {
Object.keys(item).forEach(key => {
text.push(key + ': ' + item[key]);
});
}
return text.join('\r\n'); // \r\n is the line break
}

You can use json pipe to format your object into a json string:
[(ngModel)]="mainStepText | json"
If you want to show a specific property of your object, you can access it in your template:
[(ngModel)]="mainStepText.data[0].title"
This will display "Test1" in your field.

You could loop through your json.data and through their keys to extract the text and values and generate the string you need for the text area.
const text = [];
for (let item of this.textVar.data) {
Object.keys(item).forEach(key => {
text.push(key + ': ' + item[key]);
});
}
return text.join('\r\n'); // \r\n is the line break
Here's the running code, I put it in app.ts: http://plnkr.co/edit/3AbQYQOW0MVBqO91X9qi?p=preview
Hope this is of help.

Related

How to iterate over JSON returned by HttpClient

I have a simple Angular HttpClient, which is correctly returning JSON. I am attempting to cast the results to enforce type safety (not sure if this is correct).
But how do I actually access the returned JSON to copy it into an array?
The httpClient get() request is (and seems to be working fine):
public sendGetRequest(): Observable<Symbols[]> {
return this.httpClient.get<Symbols[]>(this.REST_API_SERVER);
}
The Symbols interface is
export interface Symbols {
code: string
desc: string
}
I have a component which calls the data service and is getting a response. However the code below returns an error when attempting to map the JSON into a string array
ERROR TypeError: syms.map is not a function
listOfOption: Array<{ value: string; label: string }> = []
this.dataService.sendGetRequest().subscribe((syms: Symbols[]) => {
console.log('return value ' + JSON.stringify(syms))
// console output shows the returned JSON and it looks correct
//this does not work, how do I copy the results to a string array??
this.listOfOption = syms.map(results => {
return {
value: results.code,
label: results.code,
}
})
})
The JSON data structure is:
{
"results": [
{
"code": "code1",
"desc": "Long description of code 1"
},
{
"code": "code2",
"desc": "Long description of code 2"
},
{
"code": "code3",
"desc": "Long description of code 3"
},
{
"code": "code4",
"desc": "Long description of code 4"
}
]
}
This is driving me crazy
Model a new interface called responseData to support response type.
export interface responseData{
results: Symbols[]
}
export interface Symbols {
code: string
desc: string
}
Update the same in service
public sendGetRequest(): Observable<responseData> {
return this.httpClient.get<responseData>(this.REST_API_SERVER);
}
You can now retrieve the results using array.map()
listOfOption: Array<{ value: string; label: string }> = []
this.dataService.sendGetRequest().subscribe((syms: responseData) => {
console.log('return value ' + syms)
this.listOfOption = syms.results.map(result => {
return {
value: result.code,
label: result.code,
}
})
})
The response data has an object root, but you're trying to parse it as an array root. I think the simplest solution would be something like this:
public sendGetRequest(): Observable<Symbols[]> {
return this.httpClient.get<{results: Symbols[]}>(this.REST_API_SERVER)
.pipe(pluck('results'));
}
Which specifies that the response data is an object with a field named results which holds an array of Symbols.
Alternatively you could also extract the response type to a separate definition:
interface ApiResponse {
results: Symbols[]
}
public sendGetRequest(): Observable<Symbols[]> {
return this.httpClient.get<ApiResponse>(this.REST_API_SERVER)
.pipe(pluck('results'));
}

How to get data from database in array format using node js and MySql

I am using node.js as server language and Mysql as database so I am running query and getting data from database but is is showing in format like this
[ BinaryRow { name: 'Dheeraj', amount: '77.0000' },
BinaryRow { name: 'Raju', amount: '255.0000' } ]
What I want is
['Dheeraj', 77.0000],
['Raju', 66255.000030],
This what I am doing in my backend (node.js):
My model:
static getChartData(phoneNo, userType) {
let sql = 'select businessname as name,sum(billamt) amount from cashbackdispdets where consphoneno =' + phoneNo + ' group by businessid order by tstime desc limit 10'
return db.execute(sql, [phoneNo]);
My controller:
exports.getColumnChart = function(req, res) {
const phoneNo = req.body.userId
const userType = req.body.userType
console.log(phoneNo)
dashboardModule.getChartData(phoneNo, userType)
.then(([rows]) => {
if (rows.length > 0) {
console.log(rows)
return res.json(rows)
} else {
console.log("error")
return res.status(404).json({ error: 'Phone No. already taken' })
}
})
.catch((error) => {
console.log(error)
return res.status(404).json({ error: 'Something went wrong !!' })
})
}
I am sending this data to Ui and when I am receiving it on UI it is in the form of object inside array which is not the required data type I want
axios().post('/api/v1/Dashboard/DashboardColumnChart',this.form)
.then(res=>{
console.log(res.data)
debugger
this.chartData= res.data
})
The above code consoles on browser like
I am not getting any idea how o do it should I do it with backend or with front end and how
Nodejs will send you a JSON response if you want to change it. It is better to change or maniuplate it in a Front end framework. But if you want to change it in backend as you have asked Make sure that the rows is in the format that you want to recive.
let data = [
{ "name": "Dheeraj", "amount": "77.0000" },
{ "name": "Raju", "amount": "255.0000" }
]
// empty array to store the data
let testData = [];
data.forEach(element => {
testData.push(element.name)
});
You can format it using array.map and Object.values. map functions loops over each element and returns a modified element according to the callback provided. Object.values simply returns all the values of an object in an array.
const data = [ { "name": "Dheeraj", "amount": "77.0000" }, { "name": "Raju", "amount": "255.0000" } ];
const formattedData = data.map(obj => Object.values(obj));
console.log("Initial Data: ", data);
console.log("Formatted Data: ", formattedData);
// Map function example
const a = [1,2,3]
const mappedA = a.map(e => e * 2)
console.log(a, " mapped to: ", mappedA);
// Object.values example
const b = { firstName: 'John', lastName: 'Doe', number: '120120' }
console.log(Object.values(b));

best way to pass an array of object with activeroute - Angular

I'm trying to pass an array of objects through activeroute. When I pass it to the next page I get [object Object]. I saw a question on Stackoverflow where they use JSON.stringify but that didn't work for me. Or is it better to use application providers instead of queryparams.
TS of page sending the data
criteriaList: ShipmentLookupCriteria[] = [];
navigateTo() {
const navigationExtras: NavigationExtras = {
queryParams: {
criteriaList: this.criteriaList
}
};
this.router.navigate(['/lookup/results'], navigationExtras);
}
TS of page receiving the data
this.sub = this.route.queryParams.subscribe(params => {
console.log(params.criteriaList);
});
ShipmentLookUpCriteria model
import { EquipReferenceTuple } from './equip-reference-tuple.model';
export class ShipmentLookupCriteria {
terminal: string;
equipReferenceList: EquipReferenceTuple[];
constructor(terminal: string, equipReferenceList: EquipReferenceTuple[]) {
this.terminal = terminal;
this.equipReferenceList = equipReferenceList;
}
}
UPDATE
I decided to start with something simple. So I create an array of objects with dummy data.
navigateTo() {
const navigationExtras: NavigationExtras = {
queryParams: {
criteriaList: [{ name: 1, age: 1 }, { name: 2, age: 2 }]
}
};
this.router.navigate(['lookup/results'], navigationExtras);
}
PAGE RECEIVING THE PARAMS
this.route.queryParams.subscribe(params => {
console.log(params.criteriaList[0]);
});
RETURNS = [object Object] If I do again JSON.stringify it shows it as string "[object Object]". if I do params.criteriaList[0].name returns undefined
You can simply pass,
this.router.navigate(['/lookup/results'], {queryParams: {criteriaList: this.criteriaList }});
and access it using
this.sub = this.route.snapshot.queryParamMap.get('criteriaList');

How to append JSON data to existing JSON file node.js

How to append an existing JSON file with comma "," as separator
anchors = [ { "title":" 2.0 Wireless " } ]
fs.appendFileSync('testOutput.json', JSON.stringify(anchors));
This current code's output is like this
[
{
"title":" 2.0 Wireless "
}
]
[
{
"title":" Marshall Major II "
}
]
How to I get this in the correct format with comma "," as separator
I want to get something like this
[
{
"title":" 2.0 Wireless "
},
{
"title":" Marshall Major II "
}
]
Try this. Don't forget to define anchors array.
var data = fs.readFileSync('testOutput.json');
var json = JSON.parse(data);
json.push(...anchors);
fs.writeFile("testOutput.json", JSON.stringify(json))
I created two small functions to handle the data to append.
the first function will: read data and convert JSON-string to JSON-array
then we add the new data to the JSON-array
we convert JSON-array to JSON-string and write it to the file
example: you want to add data { "title":" 2.0 Wireless " } to file my_data.json on the same folder root. just call append_data (file_path , data ) ,
it will append data in the JSON file, if the file existed . or it will create the file and add the data to it.
data = { "title":" 2.0 Wireless " }
file_path = './my_data.json'
append_data (file_path , data )
the full code is here :
const fs = require('fs');
data = { "title":" 2.0 Wireless " }
file_path = './my_data.json'
append_data (file_path , data )
async function append_data (filename , data ) {
if (fs.existsSync(filename)) {
read_data = await readFile(filename)
if (read_data == false) {
console.log('not able to read file')
}
else {
read_data.push(data)
dataWrittenStatus = await writeFile(filename, read_data)
if dataWrittenStatus == true {
console.log('data added successfully')
}
else{
console.log('data adding failed')
}
}
else{
dataWrittenStatus = await writeFile(filename, [data])
if dataWrittenStatus == true {
console.log('data added successfully')
}
else{
console.log('data adding failed')
}
}
}
async function readFile (filePath) {
try {
const data = await fs.promises.readFile(filePath, 'utf8')
return JSON.parse(data)
}
catch(err) {
return false;
}
}
async function writeFile (filename ,writedata) {
try {
await fs.promises.writeFile(filename, JSON.stringify(writedata,null, 4), 'utf8');
return true
}
catch(err) {
return false
}
}

How to i display file from JSON object which contains an array?

Below is my json object which is returned. As you can see i have an array called "DocumentVersions" with a blob address of the file that i want to display. On the success function i want to display the image under a div. I tried looping through but i don't know how to display the image. I could have multiple files returned.
{
"FileUploadID":"27",
"DocumentVersions":[
{
"Active":true,
"DocumentVersionID":"5",
"FileName":"Logo0112.png",
"ContentLength":18846,
"ContentType":"image/png", "
"RevisionNumber":0,
"RevisionDate":"2017-08-01T12:24:04.7748026+01:00",
"Blob":"https://address/documents/75755df4af5f.png",
"BlobFileName":75755df4af5f.png"
}
],
"success":true,
"id":"27",
"message":"The Files have been uploaded"
}
Here is my success function. Where i get a 'Cannot read property 'Blob' of undefined'
myDiv.on("complete", function (data) {
res = JSON.parse(data.xhr.responseText);
console.log(res);
if (res.success == true) {
for (var key in res) {
var optionhtml = '<p="' + res[key].FileUploadID +
'">' + res[key].DocumentVersions.Blob + '</p>';
$(".test").append(optionhtml);
}
}
else {
alert(res.message);
}
});
As you can see, the DocumentVersions is not a object, it's a array with objects (only one object in this case).
{
"FileUploadID":"27",
"DocumentVersions":[
{
"Active":true,
"DocumentVersionID":"5",
"FileName":"Logo0112.png",
"ContentLength":18846,
"ContentType":"image/png", "
"RevisionNumber":0,
"RevisionDate":"2017-08-01T12:24:04.7748026+01:00",
"Blob":"https://address/documents/75755df4af5f.png",
"BlobFileName":75755df4af5f.png"
}
],
"success":true,
"id":"27",
"message":"The Files have been uploaded"
}
You need to specify the inner object in the array that you want to get data:
res[key].DocumentVersions[0].Blob
Thanks for your help, I solved my problem by using the following code this lets me get the image files and display.
res.DocumentVersions.forEach(function (obj) {
var img = new Image();
img.src = obj.Blob;
img.name = obj.FileName;
img.setAttribute("class", "fileLoad");
$("#fileupload").append(img);
});