Vue won't read JSON response? - json

If /scheduled_jobs/list returns a JSON object, why is my Vue component not reading it?
Here's the component:
<template>
<div>
<ul v-if="jobs.length">
<li v-for="job in jobs">
{{ job.id }}
{{ job.document_id }}
{{ job.user_id }}
{{ job.schedule }}
{{ job.status }}
</li>
</ul>
<p v-else>
Nothing waiting.
</p>
</div>
</template>
<script>
export default {
data () {
return {
jobs: []
}
},
methods: {
loadData () {
$.get('/scheduled_jobs/list', function (response) {
this.jobs = response.json()
}.bind(this))
},
ready () {
this.loadData()
setInterval(function () {
this.loadData()
}.bind(this), 30000)
}
}
}
</script>
And here's the response from the URL:
{
"id": "8154e79383a950072823410e",
"document_id": 59455,
"user_id": 2,
"schedule": "2018-02-03T12:00",
"status": 2
}
I just get this response:
Nothing waiting.

you are overwriting the array with an object:
methods: {
loadData () {
$.get('/scheduled_jobs/list', function (response) {
this.jobs.push(response.json());
}.bind(this))
}

You're getting an object, not an array, so jobs.length is undefined.

Related

Parse HTML from a nested JSON file with AngularJS

I am trying to parse nested JSON with AngularJS. There are items in it which will used throughout the page, however there are also nested news items in there. I'm not sure how to work this out.
test.json
{
"CustomerName" : "TEST",
"PaidCustomer" : true,
"LaunchEndDate" : "24-07-2021",
"LauncherTitle" : "Launcher Title",
"LauncherSlogan" : "LauncherSlogan",
"CommunityLogo" : "logo.jpg",
"news" : [
{
"Title" : "News 1",
"Description" : "Newsmessage 1",
"FeaturesImage" : "",
"Author" : "Hutserino",
"Tags" : [ "#launcher", "#HellYeah" ],
},
{
"Title" : "News 2",
"Description" : "news 2",
"FeaturesImage" : "",
"Author" : "Hutserino",
"Tags" : [ "#launcher", "#HellYeah" ]
}
]
}
I've already tried this:
Angular code
<script>
(function() {
angular.module('myApp', []);
function myController($scope, $http) {
return $http.get('launcher.json')
.then(function(response) {
return response.data;
});
return {
LauncherTitle: LauncherTitle,
LauncherSlogan: LauncherSlogan
}
var data = response.data;
data.forEach(data.news, function(clientdata.news, index) {
angular.forEach(clientdata.news, function(newsitem, index){
$scope.news.push(newsitem);
});
});
}
})();
</script>
HTML
<div ng-app="myApp" ng-controller="myController">
<h1 class="display-3">{{ GameLauncherTitle }}</h1>
<h3 class="display-5">{{ GameLauncherSlogan }}</h3>
<div class="card-columns">
<div class="card" ng-repeat="newsitem in news">
<img src="{{ newsitem.FeaturesImage }}" class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title text-dark">{{ newsitem.Title }}</h5>
<p class="card-text text-dark">{{ newsitem.Description }}</p>
</div>
</div>
</div>
</div>
But this isn't returning any results.
You are quitting out of your myController function with the two returns, I think you might have been trying
(function() {
var myApp = angular.module('myApp', []);
myApp.controller('myController', function($scope, $http) {
$scope.news = []
$http.get('launcher.json')
.then(function(r) {return JSON.parse(r)})
.then(function(response) {
response.news.forEach(function(newsitem){
$scope.news.push(newsitem);
});
});
});
})();
Can you try this instead of your Angular Code?
Cleaned version:
(() => {
const myApp = angular.module('myApp', []);
myApp.controller('myController', ($scope, $http) => {
$scope.news = []
$http.get('launcher.json')
.then(r => JSON.parse(r))
.then(response => {
response.news.forEach(function (newsitem) {
$scope.news.push(newsitem);
})
})
})
})();

Iteration of json file in typescript in angular?

[
{
"title": "Marker 1",
"innercontent": "the Porcelain Factory"
},
{
"title": "Marker 2",
"innercontent": "The Taj Mahal "
},
{
"title": "Marker 3",
"innercontent": "Golconda Fort"
}
]
The above is my json file.
<div *ngFor="let marker of currentmrkr">
<div>
{{ marker.title }}
</div>
<div>
{{ marker.innercontent }}
</div>
</div>
The above is my html file.
import * as content from './content.json';
marker.addListener("click", () => {for(let item of content){
if(marker.getTitle() == item.title){
this.currentmrkr = item;
}
}
}
The above is in my typescript file.
This shows an error like -
core.js:6260 ERROR TypeError: _content_json__WEBPACK_IMPORTED_MODULE_1___namespace is not iterable
How can we iterate through the json object inside the typescript file in angular and how to import the file into typescript?
If you want to iterate JSON within Typescript logic for let's say pushing data to firebase, you can use library called Lodash
import * as _ from 'lodash';
myfunction(json) {
return new Promise((resolve) => {
_.map(json, (e, i) => {
_.keys(e).map(() => {
this.afs.collection('library').doc('doc ' + i).set(e);
})
})
resolve();
})
}
I have a full blog on this if you need more details. Else if you defined a simple json object in typescript and want to view particular value in HTML you can use the following approach:
import { Component } from "#angular/core";
#Component({
selector: "app-some-section",
templateUrl: "./some-section.component.html",
styleUrls: ["./some-section.component.scss"],
})
export class SomeSectionComponent {
users = [
{
name: "Jacob",
job: "Analyst",
city: "California",
},
{
name: "John",
job: "Founder",
city: "New York",
},
];
constructor() {}
}
and then in the HTML template:
<div class="card" *ngFor="let user of users">
<h3 class="job">{{ user.job }}</h3>
<h3 class="name">{{ user.name }}</h3>
<h3 class="city">{{ user.city }}</h3>
</div>

Access an axios data formatted as json from vue

I need to show data from a json response from get request. Vue part of my code is :
<script type="text/javascript">
var vm = new Vue({
el: '#app2',
delimiters: ['[[',']]'],
data: {
masa_data: {},
},
mounted: function() {
polling1=setInterval(function() {
axios.get('/order')
.then(function(response) {
vm.$data.masa_data = response.data;
})
}, 1000);
},
beforeDestroy () {
clearInterval(this.polling1)
}
});
</script>
masa_data comes from axios as below:
{ "Bahçe1": { "A": { "1": { "kisi_sayisi": "2", "siparisler": [ {
"adet": 2, "bolum": "drink", "satir": "Açık Çay" }, { "adet": 1,
"bolum": "tatli", "satir": "Kaymaklı Ekmek Kadayıfı" } ] },
When i want to show, for example, value of "kisi_sayisi", I could not figure out what to put inside html code below:
<p class="card-text">[[masa_data]]</p>
Try this.
<p class="card-text" v-if="Object.values(masa_data).length>0">[[masa_data.Bahce1.A['1']['kisi_sayisi'] ]]</p>
https://codepen.io/Pratik__007/pen/QWbjOxE?editors=1010

vue-chartjs in laravel,vuejs using API Axios

I am trying to show the all the companies in the Chart in Dashboard.vue regarding years but it does not show anything and I am trying since many days if someone could help me it will be so kind of him.
My API/Route is :
Route::apiResources(['company'=>'API\CompanyController']);
EmployeeController code is :
public function index(){return Employee::all();}
Code in Chart.vue is:
<script>
import { Line } from "vue-chartjs";
export default {
extends: Line,
data() {
return {
url: "api/company",
years: [],
labels: [],
data: ""
};
},
methods: {
getProducts() {
axios.get(this.url).then(response => {
this.data = response.data;
if (this.data) {
this.data.forEach(element => {
this.years.push(element.created_at);
this.labels.push(element.name);
});
this.renderChart(
{
labels: this.years,
datasets: [
{
label: "list of Companies ",
backgroundColor: "#f87979",
data: this.name
}
]
},
{ responsive: true, maintainAspectRatio: false }
);
} else {
console.log("NO DATA");
}
});
}
},
mounted() {
this.getProducts();
}
};
</script>
Code in app.js is :
Vue.component('chart-component', require('./components/Chart.vue'));
code in Dashboard is :
<template>
<div class="container">
<chart-component></chart-component>
</div>
</template>
I solved it the problem was that I did not put the .default so I amend it like below:
Vue.component('chart-component', require('./components/Chart.vue').default);

The componentDidMount is not getting called in reactjs

I'm trying the example in reactjs tutorial https://facebook.github.io/react/docs/tutorial.html to read the json from server(file). But, my "componentDidMount" is not getting called.
Below is the code:
var CommentBox = React.createClass({
loadCommentsFromServer: function() {
$.ajax({
url: this.props.url,
dataType: 'json',
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this),
cache: false
});
},
getInitialState: function() {
return {data: {}};
},
componentDidMount: function() {
this.loadCommentsFromServer();
},
render: function() {
return (
<div className="commentBox">
<h1>Comments</h1>
<CommentList data={this.state.data} />
</div>
);
}
});
var CommentList = React.createClass({
render: function() {
var commentNodes = this.props.data.content.map(function(comment) {
return (
<Comment pageName={comment.xyz} key={comment.id}>
{comment.abc}
</Comment>
);
});
return (
<div className="commentList">
{commentNodes}
</div>
);
}
});
var Comment = React.createClass({
render: function() {
return (
<div className="comment">
<h2 className="commentpageName">
{this.props.pageName}
</h2>
<p> {this.props.children} </p>
</div>
);
}
});
ReactDOM.render(<CommentBox url="/api/comments" />, document.getElementById('content'));
Please check the way I have initialized the data(data: {})
The "componentDidMount" gets called when the json is of the following type(Just the way in the tutorial):
[ {"id": "1", "xyz": "xyz1", "abc": "abc1"},
{"id": "2", "xyz": "xyz2", "abc": "abc2"} ]
But the json format I want is:
{
content: [
{"id": "1", "xyz": "xyz1", "abc": "abc1"},
{"id": "2", "xyz": "xyz2", "abc": "abc2"},
{"id": "3", "xyz": "xyz3", "abc": "abc3"}],
"totalPages":3,
"totalElements":10,
"last":true
}
Let me know in what conditions the componentDidMount doesn't get called. Please help.
In the "Networks" console of chrome developer tools, I don't see the call made to my json file.
When I added logs in my program, I see that getInitialState() gets called first, then render, then the error "Uncaught TypeError: Cannot read property 'data' of null" is shown.
I think your componentDidMount() is not called because your render code inside <CommentList> does not work on first render, because data is empty, and this.props.data.content probably does not exist, therefore your render fails.
What you probably should do is change this:
var commentNodes = this.props.data.content.map(function(comment) {
To this:
var commentNodes = [];
if (this.props.data.content) {
commentNodes = this.props.data.content.map(function(comment) {
...
}
componentDidMount() is always called after the first render (and not in subsequent renders)