In my Navigation I want to insert Links from my CMS. I am using Axios. My Navigation is Vue. How do I get the data from the JSON file into the const?
Just knowing if I need to search for the solution in Axios or in Vue would help alot too.
import axios from "axios";
const exhibitions = [
{
name: "Exhibition 1",
description: "Info 1",
href: "#",
},
{
name: "Exhibition 2",
description: "Info 2",
href: "#",
},
];
my export default:
export default {
name: "item",
data() {
return {
info: null,
};
},
mounted() {
axios
.get("http://localhost:8000/posts.json")
.then((response) => (this.info = response));
},
posts.json
{
"data":
[{
"id":1028,
"title":"Exhibition 1",
"slug":"exhibition-2009",
"url":"http://localhost:8000/exhibitions/exhibition-2009"
},
{
"id":905,
"title":"Exhibition 2",
"slug":"exhibition-2006",
"url":"http://localhost:8000/exhibitions/exhibition-2006"
}],
"meta":
{
"pagination":
{
"total":2,
"count":2,
"per_page":100,
"current_page":1,
"total_pages":1,
"links":{}
}
}
}
What do you mean by "Get the data from the JSON into the const"??
Just a reminder, a constant cannot be modified.
According to what you commented, I guess that you'd like to store the data fetched from your json file to info variable. And then, render your links in the navigation bar.
mounted() {
axios
.get("http://localhost:8000/posts.json")
.then((response) => (this.info = response));
}
Once the component is mounted you're fetching your JSON data from the file using Axios. When the promise is accepted then you store the response data to this.info. Once you have your data in that variable you can render everything ⬇️
There's a directive in VueJS for list rendering called v-for. You can use it to render all the links to your navigation bar.
<ul id="navigation-bar">
<li v-for="i in info">
{{ i.title }}
</li>
</ul>
HttpClient.get in Angular 5 is not returning data if data is in a nested json format. The code below works for non-nested json data.
Would you please let me know if I miss anything or what would be a way to get the data?
Code:
import { HttpClient, HttpHeaders, HttpErrorResponse } from '#angular/common/http';
export class ReportService {...
searchByUser(userUrl: string): Observable<any> {
console.log('userUrl', userUrl);
return this.httpClient
.get(userUrl, { responseType: 'json' })
.catch((error: HttpErrorResponse) => {
return Observable.throw(error.status)
});
}
}
import { ReportService } from '../report.service';
this.reportService.searchByUser(userUrl).subscribe(data => {
console.log("Data :", data);
});
Nested JSON Sample Data returned by the userUrl:
[
{
"userId": "JX",
"location": "CHANTILLY, XX",
"fullName": "SMITH, JX L",
"userType": "P",
"userStatusDesc": "Active",
"occupationInfo": {
"occupationTitle": "HR GENERALIST HQ"
},
"miscInfo": {
"rankingPoints": 15,
"searchTermCount": 1
}
}
]
It looks like the issue was not with the HttpClient or nested JSON. I was able to have it working with the same JSON generated locally. And when I deployed the code it worked with the JSON generated under the same proxy.
I am new to code Angular 2. My question is how to show JSON Format A with a proper formatting. As shown, the result includes whole objects (named Atom) I want to display.
If JSON format looks like B, I can show it using ngFor well. However, in the Json format A, I have to create multiple Atom objects explicitly from result then I can show them using NgFor.
I do not have sufficient knowledge about Angular 2 and JSON, if you have some idea about this, could you give me some guide for this and which way could be desirable solution?
Json Format A
{
"pageS": 25,
"pageN": 1,
"pageC": 2,
"result": [
{
"type": "A",
"id": "2425",
"tree": "false"
},
{
"type": "A",
"id": "1185",
"tree": "false"
},
{
"type": "A",
"id": "2680",
"tree": "false"
},
]
}
Json Format B
[
{"type":"A", "id": "2425", "tree":"false"},
{"type":"A", "id": "1185", "tree":"false"},
{"type":"A", "id": "2680", "tree":"false"}
]
app.component.ts
import {Component} from 'angular2/core';
import {Router} from 'angular2/router';
import {AtomService} from './service/atom';
import {User} from './datatype/User';
#Component({
selector: 'my-app',
template: `
<ul>
<li *ngFor="#atom of atoms">
{{atom.id}}
</li>
</ul>
`,
providers: [AtomService]
})
export class AppComponent {
atoms: Array<Atom>;
constructor(private service : AtomService) {
service.getAtoms().subscribe(res => this.atoms = res);
}
}
atom.service
import { Injectable } from 'angular2/core';
import { Http, Response } from 'angular2/http';
import 'rxjs/add/operator/map';
import {Atom} from '../datatype/Atom';
#Injectable()
export class AtomService {
constructor(private http: Http) {
this.http = http;
}
getAtoms() {
return this.http.get('./app/api/atoms.json')
.map( (responseData) => {
return responseData.json();
})
.map((atoms: Array<any>) => {
let result:Array<Atom> = [];
if (atoms) {
atoms.forEach((atom) => {
result.push(new Atom(atom.type, atom.id, atom.tree));
});
}
return result;
});
}
}
I'm not sure I understand what exactly do you want. You can read the results directly from the response, if you don't want to iterate and create new Atom objects.
<ul>
<li *ngFor="#atom of data.result">
{{atom.id}}
</li>
</ul>
But I think the way you have it now is actually better, as you should process the data, even though you can bind HTML directly to the result.
I am having problems parsing a serialized JSON Ajax Get request (using jQuery $.ajax) send to my express.js 4 server. The data send as a JSON request is generated by datatables.
Here is how I started on the client-side
$(document).ready(function() {
$('#example').dataTable( {
"bServerSide": true,
"fnServerData": function (sSource, aoData, fnCallback) {
$.ajax({
"dataType": 'json',
contentType: 'application/json',
"type": "GET",
"url": "http://localhost:3000/ajax/phenotypes/withOrg/like/datatables/",
"data": aoData,
"success": fnCallback,
"error": function () {
alert('have some problem');
}
});
}
} );
} );
when I load this code in the brower datatables generates the following GET request URL (to the server):
GET
/ajax/phenotypes/withOrg/like/datatables/?draw=1&columns=%5Bobject+Object%5D%2C%5Bobject+Object%5D%2C%5Bobject+Object%5D%2C%5Bobject+Object%5D%2C%5Bobject+Object%5D%2C%5Bobject+Object%5D&order=%5Bobject+Object%5D&start=0&length=10&search=%5Bobject+Object%5D
or in decoded form (output from firebug)
columns [object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
draw 1
length 10
order [object Object]
search [object Object]
start 0
so I serialized the data before sending
$(document).ready(function() {
$('#example').dataTable( {
"bServerSide": true,
"fnServerData": function (sSource, aoData, fnCallback) {
var myData = JSON.stringify(aoData);
$.ajax({
"dataType": 'json',
contentType: 'application/json',
"type": "GET",
"url": "http://localhost:3000/ajax/phenotypes/withOrg/like/datatables/",
"data": myData,
"success": fnCallback,
"error": function () {
alert('have some problem');
}
});
}
} );
} );
here is the generated GET parameters from datatables:
GET
/ajax/phenotypes/withOrg/like/datatables/?[{%22name%22:%22draw%22,%22value%22:1},{%22name%22:%22columns%22,%22value%22:[{%22data%22:0,%22name%22:%22%22,%22searchable%22:true,%22orderable%22:true,%22search%22:{%22value%22:%22%22,%22regex%22:false}},{%22data%22:1,%22name%22:%22%22,%22searchable%22:true,%22orderable%22:true,%22search%22:{%22value%22:%22%22,%22regex%22:false}},{%22data%22:2,%22name%22:%22%22,%22searchable%22:true,%22orderable%22:true,%22search%22:{%22value%22:%22%22,%22regex%22:false}},{%22data%22:3,%22name%22:%22%22,%22searchable%22:true,%22orderable%22:true,%22search%22:{%22value%22:%22%22,%22regex%22:false}},{%22data%22:4,%22name%22:%22%22,%22searchable%22:true,%22orderable%22:true,%22search%22:{%22value%22:%22%22,%22regex%22:false}},{%22data%22:5,%22name%22:%22%22,%22searchable%22:true,%22orderable%22:true,%22search%22:{%22value%22:%22%22,%22regex%22:false}}]},{%22name%22:%22order%22,%22value%22:[{%22column%22:0,%22dir%22:%22asc%22}]},{%22name%22:%22start%22,%22value%22:0},{%22name%22:%22length%22,%22value%22:10},{%22name%22:%22search%22,%22value%22:{%22value%22:%22%22,%22regex%22:false}}]
HTTP/1.1
in decoded form (output from firebug and beautified using an online tool- checked with jslint, seems correct!)
[
{
"name":"draw",
"value":1
},
{
"name":"columns",
"value":[
{
"data":0,
"name":"",
"searchable":true,
"orderable":true,
"search":{
"value":"",
"regex":false
}
},
{
"data":1,
"name":"",
"searchable":true,
"orderable":true,
"search":{
"value":"",
"regex":false
}
},
{
"data":2,
"name":"",
"searchable":true,
"orderable":true,
"search":{
"value":"",
"regex":false
}
},
{
"data":3,
"name":"",
"searchable":true,
"orderable":true,
"search":{
"value":"",
"regex":false
}
},
{
"data":4,
"name":"",
"searchable":true,
"orderable":true,
"search":{
"value":"",
"regex":false
}
},
{
"data":5,
"name":"",
"searchable":true,
"orderable":true,
"search":{
"value":"",
"regex":false
}
}
]
},
{
"name":"order",
"value":[
{
"column":0,
"dir":"asc"
}
]
},
{
"name":"start",
"value":0
},
{
"name":"length",
"value":10
},
{
"name":"search",
"value":{
"value":"",
"regex":false
}
}
]
the problem is now that this stringified URL can not be parsed on the express 4 server side
I use express4 req.query and url.parse method for this : http://expressjs.com/api.html#req.query
and then try to parse the received json string with the JSON.parse() method
...
var url = require('url');
...
router.get('/withOrg/like/datatables/', function (req, res) {
console.log('getting json string via req.query');
console.log(req.query);
console.log('output parsed json object using JSON.parse');
console.log(JSON.parse(req.query));
//another try
console.log('for stack overflows test 2');
console.log(url.parse(req.url, true).query);
console.log('output parsed json object using JSON.parse');
console.log(url.parse(req.url, true).query);
})
both json string output results are invalid json as you can see here and unable to parse with JSON.parse:
getting json string via req.query
{
'{"data":0,"name":"","searchable":true,"orderable":true,"search":{"value":"","regex":false}},{"data":1,"name":"","searchable":true,"orderable":true,"search":{"value":"","regex":false}},{"data":2,"name":"","searchable":true,"orderable":true,"search":{"value":"","regex":false}},{"data":3,"name":"","searchable":true,"orderable":true,"search":{"value":"","regex":false}},{"data":4,"name":"","searchable":true,"orderable":true,"search":{"value":"","regex":false}},{"data":5,"name":"","searchable":true,"orderable":true,"search":{"value":"","regex":false}}':
{ '{"column":0,"dir":"asc"}': '' } }
output parsed json object using JSON.parse
getting json string via req.query
{
'{"data":0,"name":"","searchable":true,"orderable":true,"search":{"value":"","regex":false}},{"data":1,"name":"","searchable":true,"orderable":true,"search":{"value":"","regex":false}},{"data":2,"name":"","searchable":true,"orderable":true,"search":{"value":"","regex":false}},{"data":3,"name":"","searchable":true,"orderable":true,"search":{"value":"","regex":false}},{"data":4,"name":"","searchable":true,"orderable":true,"search":{"value":"","regex":false}},{"data":5,"name":"","searchable":true,"orderable":true,"search":{"value":"","regex":false}}':
{ '{"column":0,"dir":"asc"}': '' } }
output parsed json object using JSON.parse
when I try to parse the json string I get the error from JSON.parse
SyntaxError: Unexpected token o
at Object.parse (native)
at module.exports (/Users/xxx/yyy/routes/phenotypesAJAX.js:16:19)
at Layer.handle [as handle_request] (/Users/xxx/yyy/node_modules/express/lib/router/layer.js:82:5)
at next (/Users/xxx/yyy/node_modules/express/lib/router/route.js:100:13)
Is this a bug in express 4?
I cannot see where the problem is. On the client-side the serialized datatable GET request seems valid (checked with JSLint). On the express4 server side I cannot find any other way to parse the GET request in a different way.
Thank you so much for your help,
Oliver
I have got the answer from posting this problem at the express github bugtracker.
Lesson learned:
I was thinking to complicated, express.js request methods are not written especially for a specific request format! They just use the data format which was send to them without modification!
The method I used first:
req.query
[..] only works with standard query strings, which are key=value pairs,
which the URL you gave was not.[..]
The correct method to solve my problem is:
url.parse(req.url).query
returns the complete parameter string of an URL which than has to be decoded manually:
obj = JSON.parse(decodeURIComponent(query))
Here is the full explanation:
https://github.com/strongloop/express/issues/2460