Alternative way to fetch value from a local json file using $http - javascript

I want to load countries list from a countries json file stored locally. I have included the file in index.html as:
<!-- Including Json -->
<script src="json/countries.json"></script>
The Json file is saved in json folder with name countries.json, the file contents are as:
[
{
"country_id":"1",
"country_name":"Afghanistan"
},
{
"country_id":"2",
"country_name":"Albania"
},
{
"country_id":"3",
"country_name":"Algeria"
},
{
"country_id":"4",
"country_name":"American Samoa"
},
{
"country_id":"5",
"country_name":"Andorra"
},
{
"country_id":"6",
"country_name":"Angola"
},
{
"country_id":"7",
"country_name":"Anguilla"
},
{
"country_id":"8",
"country_name":"Antarctica"
},
{
"country_id":"9",
"country_name":"Antigua and Barbuda"
},
{
"country_id":"10",
"country_name":"Argentina"
},
{
"country_id":"11",
"country_name":"Armenia"
},
{
"country_id":"12",
"country_name":"Aruba"
},
{
"country_id":"13",
"country_name":"Australia"
},
{
"country_id":"14",
"country_name":"Austria"
},
{
"country_id":"15",
"country_name":"Azerbaijan"
},
{
"country_id":"16",
"country_name":"Bahamas"
},
{
"country_id":"17",
"country_name":"Bahrain"
},
{
"country_id":"18",
"country_name":"Bangladesh"
},
{
"country_id":"19",
"country_name":"Barbados"
},
{
"country_id":"20",
"country_name":"Belarus"
},
{
"country_id":"21",
"country_name":"Belgium"
},
{
"country_id":"22",
"country_name":"Belize"
},
{
"country_id":"23",
"country_name":"Benin"
},
{
"country_id":"24",
"country_name":"Bermuda"
}
]
To just name a few countries.
I could successfully parse the data and populate it to the UI from my controller referring the $htttp.get() service of angular as suggested by #jaime:
//Getting the base url inorder to tell app where to find countries json
var baseUrl = $location.absUrl().substring(0, $location.absUrl().indexOf('www'));
//Fetching the countries Json
return $http.get(baseUrl+'www/json/countries.json')
//On Fetching the countries lsit
.then( function(response){
$scope.countryList = response.data;
});
It works well, no doubt about it. But is there another alternative to achieve this functionality? Without using the $http.get()? I came accross angular.fromJson(), but it won't parse a file path as it requires it's argument to be a json object. Also I came across alternatives using jquery as in https://stackoverflow.com/a/12091134/1904479. is there any other alternative which doesn't require jquery, Instead uses angular or ionic code?

Actually, we can use it, by declaring it in a constants file as:
Step 1) Create a file constants.jsand add the json object into it:
var ConstantsCountries = [
{
"country_id":"1",
"country_name":"Afghanistan"
},
{
"country_id":"2",
"country_name":"Albania"
},
{
"country_id":"3",
"country_name":"Algeria"
},
{
"country_id":"4",
"country_name":"American Samoa"
},
{
"country_id":"5",
"country_name":"Andorra"
},
{
"country_id":"6",
"country_name":"Angola"
},
{
"country_id":"7",
"country_name":"Anguilla"
},
{
"country_id":"8",
"country_name":"Antarctica"
},
{
"country_id":"9",
"country_name":"Antigua and Barbuda"
},
{
"country_id":"10",
"country_name":"Argentina"
},
{
"country_id":"11",
"country_name":"Armenia"
},
{
"country_id":"12",
"country_name":"Aruba"
},
{
"country_id":"13",
"country_name":"Australia"
},
{
"country_id":"14",
"country_name":"Austria"
},
{
"country_id":"15",
"country_name":"Azerbaijan"
},
{
"country_id":"16",
"country_name":"Bahamas"
},
{
"country_id":"17",
"country_name":"Bahrain"
},
{
"country_id":"18",
"country_name":"Bangladesh"
},
{
"country_id":"19",
"country_name":"Barbados"
}
]
Step 2: Include the js file in the index.html as:
<!-----Constants Classes---->
<script src="Constants/Constants.js"></script>
Step 3: Use it in your controller as:
.controller('CountriesCtrl', function ($localStorage,$rootScope,$location,$ionicLoading,$ionicHistory,$timeout) {
$scope.countries = ConstantsCountries;
console.log(angular.toJson($scope.countries));
}))

Related

SAPUI5 Custom MessagePopoverItem Template

I have a custom SAPUI5 application that used SAPUI5 version 1.40.11.
Since this version has been removed from CDN recently, I had to use a long-term maintenance available compatible version for the app. It is - version - 1.38.55.
I'm having an issue with MessagePopoverItem as the subtitle property is not available for this version.
So I'm trying to customize the template of the MessagePopoverItem to display the subtitle field.
While I'm trying to do this via a custom control I received the following error as it looks for a renderer.js from CDN without looking at it from the local location.
Cannot load from
https://sapui5.hana.ondemand.com/1.38.55/resources/sap/m/MessagePopoverItemRenderer.js
This is my custom controller and it's renderer.js
And I followed the below link
TooltipBaseRenderer.js: 404 - NOT FOUND
sap.ui.define([
"sap/m/MessagePopoverItem",
"./CustomMessagePopupItemRender",
], function (MessagePopoverItem,CustomMessagePopupItemRender) {
"use strict";
return MessagePopoverItem.extend("demoapp.customControls.CustomMessagePopoverItem", {
renderer:CustomMessagePopupItemRender,
metadata : {
properties: {
subtitle: {
type: "string",
defaultValue: ""
}
}
},
onAfterRendering: function() {
if(MessagePopoverItem.prototype.onAfterRendering) {
MessagePopoverItem.prototype.onAfterRendering.apply(this, arguments);
}
//...check if there is a highlight and tooltip
if(this.getTitle() !== "") {
sapMLIBContent
var oHl = this.$().find(".sapMLIBContent");
var ss = oHl;
}
}
});
});
Renderer.js
sap.ui.define([
"sap/ui/core/Renderer",
], function(Renderer) {
"use strict";
return Renderer.extend("demoapp.customControls.CustomMessagePopupItemRender", {
apiVersion: 2,
render: function(renderManager, control) {
// Issue: render function is called twice.
// See: https://github.com/SAP/openui5/issues/3169
// Update: fixed since 1.88
const child = control.getAggregation("content");
if (child && child.isA("sap.ui.core.Control")) {
renderManager.openStart("div", control)
.accessibilityState(control, { role: "tooltip" })
.style("max-width", "95vw")
.style("width", control.getWidth())
.openEnd()
.renderControl(child)
.close("div");
} else {
renderManager.openStart("span", control)
.accessibilityState(control, { role: "tooltip" })
.style("max-width", "90vw")
.style("width", control.getWidth())
.style("padding", "0.5rem")
.class("sapThemeBaseBG-asBackgroundColor")
.openEnd()
.text(control.getText())
.close("span");
}
},
});
});
Is this possible to customize the item template of the MessagePopover?
TooltipBaseRenderer.js: 404 - NOT FOUND is a completely different issue than the issue in this question. The element sap.m.MessagePopoverItem which extends sap.ui.core.Item, is not a sap.ui.core.Control but an sap.ui.core.Element. It is not supposed to have a renderer by definition.
sap.ui.core.TooltipBase, on the other hand, is a sap.ui.core.Control. It's a different issue.
Instead, you'll have to:
Extend sap.m.MessagePopoverItem by the subTitle property but without a renderer since it's not a control.
Extend the control that actually renders items using the information from your extended MessagePopoverItem element.
I have managed to extend the sap.m.MessagePopoverItem as mentioned by #Boghyon Hoffmann.
Here's the answer
CustomMessagePopoverItem.js
sap.ui.define([
"sap/m/MessagePopoverItem",
], function (MessagePopoverItem) {
"use strict";
return MessagePopoverItem.extend("demoapp.customControls.CustomMessagePopoverItem", {
metadata : {
properties: {
subtitle: {
type: "string",
defaultValue: ""
}
}
}
});
});
CustomMessagePopover.js
sap.ui.define([
"sap/m/MessagePopover",
"sap/m/StandardListItem",
"sap/ui/core/IconPool",
"./CustomMessagePopoverItem"
], function (MessagePopover,StandardListItem,IconPool,CustomMessagePopoverItem) {
"use strict";
var MessagePopover = MessagePopover.extend("demoapp.customControls.CustomMessagePopover", {
metadata : {
aggregations: {
/**
* A list with message items
*/
items: {type: "demoapp.customControls.CustomMessagePopoverItem", multiple: true, singularName: "item"},
},
},
//Override following method to add the subtitle as the description of the Standard List Item
_mapItemToListItem :function (oMessagePopoverItem) {
if (!oMessagePopoverItem) {
return null;
}
var sType = oMessagePopoverItem.getType(),
oListItem = new StandardListItem({
title: oMessagePopoverItem.getTitle(),
icon: this._mapIcon(sType),
description :oMessagePopoverItem.getSubtitle(),
type: sap.m.ListType.Navigation
}).addStyleClass(CSS_CLASS + "Item").addStyleClass(CSS_CLASS + "Item" + sType);
oListItem._oMessagePopoverItem = oMessagePopoverItem;
return oListItem;
}
});
var CSS_CLASS = "sapMMsgPopover",
ICONS = {
back: IconPool.getIconURI("nav-back"),
close: IconPool.getIconURI("decline"),
information: IconPool.getIconURI("message-information"),
warning: IconPool.getIconURI("message-warning"),
error: IconPool.getIconURI("message-error"),
success: IconPool.getIconURI("message-success")
},
LIST_TYPES = ["all", "error", "warning", "success", "information"],
// Property names array
ASYNC_HANDLER_NAMES = ["asyncDescriptionHandler", "asyncURLHandler"],
// Private class variable used for static method below that sets default async handlers
DEFAULT_ASYNC_HANDLERS = {
asyncDescriptionHandler: function (config) {
var sLongTextUrl = config.item.getLongtextUrl();
if (sLongTextUrl) {
jQuery.ajax({
type: "GET",
url: sLongTextUrl,
success: function (data) {
config.item.setDescription(data);
config.promise.resolve();
},
error: function() {
var sError = "A request has failed for long text data. URL: " + sLongTextUrl;
jQuery.sap.log.error(sError);
config.promise.reject(sError);
}
});
}
}
};
});
Here I invoke the custom control from the controller
var oMessageTemplate = new demoapp.customControls.CustomMessagePopoverItem({
type: '{TYPE}',
title: 'My Title',
description: '{DESC}',
subtitle: '{DESC}'
});
var oMessagePopover2 = new demoapp.customControls.CustomMessagePopover({
items: {
path: '/Messages',
template: oMessageTemplate
}
});

How to fetch data from an API which stream real time data

I want to use this API here,
https://developer.sportradar.com/docs/read/basketball/NCAA_Mens_Basketball_v7#tournament-summary-seeded-tournaments-only
This endpoint retrieves detailed, real-time information on every game event. I am trying to implement this in node JS. How can I do this? This API redirect to different URL whenever we hit it. Is there any way to do parse data from this? It returns response like this,
{
"heartbeat":{
"interval":5000
}
}
{
"payload":{
"game":{
"id":"0db78438-9663-470f-b3ae-1f9106298e47",
"status":"inprogress",
"coverage":"full",
"scheduled":"2021-02-27T17:00:00+00:00",
"home":{
"name":"Hoosiers",
"market":"Indiana",
"id":"c3f0a8ce-af67-497f-a750-3b859376b20a",
"points":57,
"rank":0,
"bonus":true,
"remaining_timeouts":2
},
"away":{
"name":"Wolverines",
"market":"Michigan",
"id":"bdc2561d-f603-4fab-a262-f1d2af462277",
"points":73,
"rank":3,
"remaining_timeouts":1
}
},
"event":{
"id":"a2b43bd2-1b79-4823-b76c-21a09eb1adea",
"event_type":"rebound",
"sequence":1614445806980,
"clock":"18:32",
"clock_decimal":"18:32",
"updated":"2021-10-26T16:29:17Z",
"created":"2021-02-27T17:10:06Z",
"description":"Hunter Dickinson defensive rebound",
"home_points":57,
"away_points":73,
"attribution":{
"name":"Wolverines",
"market":"Michigan",
"id":"bdc2561d-f603-4fab-a262-f1d2af462277",
"team_basket":"right"
},
"location":{
"coord_x":102,
"coord_y":236,
"action_area":"backcourt"
},
"possession":{
"name":"Wolverines",
"market":"Michigan",
"id":"bdc2561d-f603-4fab-a262-f1d2af462277"
},
"period":{
"id":"1f18ca8c-6a96-43f7-b68c-4d1b333e059c",
"number":1,
"sequence":1,
"type":"half"
},
"on_court":{
"home":{
"name":"Hoosiers",
"market":"Indiana",
"id":"c3f0a8ce-af67-497f-a750-3b859376b20a",
"players":[
{
"full_name":"Aljami Durham",
"jersey_number":"1",
"id":"6897db83-b25f-4c54-832a-0ff0c3cb86ff"
},
{
"full_name":"Rob Phinisee",
"jersey_number":"10",
"id":"481ffe40-392b-4a1b-89ec-0d9453495639"
},
{
"full_name":"Jerome Hunter",
"jersey_number":"21",
"id":"681d2cc6-24b9-4f38-8564-8c0b210a9535"
},
{
"full_name":"Trayce Jackson-Davis",
"jersey_number":"23",
"id":"c468bdc9-4778-496a-985e-7911dc6a1ff2"
},
{
"full_name":"Race Thompson",
"jersey_number":"25",
"id":"ed56bced-c614-4eeb-85ee-812edb594752"
}
]
},
"away":{
"name":"Wolverines",
"market":"Michigan",
"id":"bdc2561d-f603-4fab-a262-f1d2af462277",
"players":[
{
"full_name":"Hunter Dickinson",
"jersey_number":"1",
"id":"1d0c6b20-76b7-4a82-ae1d-20b78136525b"
},
{
"full_name":"Isaiah Livers",
"jersey_number":"2",
"id":"34736ed7-c86a-472c-8c1c-683002de6487"
},
{
"full_name":"Mike Smith",
"jersey_number":"12",
"id":"92f6b357-f6cb-40a5-8893-329425fff5ba"
},
{
"full_name":"Franz Wagner",
"jersey_number":"21",
"id":"ec3df621-2a9d-483c-9064-11b44d8841a9"
},
{
"full_name":"Eli Brooks",
"jersey_number":"55",
"id":"8869c334-f08c-4ed9-931c-9d9c657cb7bc"
}
]
}
},
"statistics":[
{
"type":"rebound",
"rebound_type":"defensive",
"team":{
"name":"Wolverines",
"market":"Michigan",
"id":"bdc2561d-f603-4fab-a262-f1d2af462277"
},
"player":{
"full_name":"Hunter Dickinson",
"jersey_number":"1",
"id":"1d0c6b20-76b7-4a82-ae1d-20b78136525b"
}
}
]
}
},
"locale":"en",
"metadata":{
"league":"NCAAM",
"match":"sd:match:0db78438-9663-470f-b3ae-1f9106298e47",
"status":"inprogress",
"team":"sd:team:bdc2561d-f603-4fab-a262-f1d2af462277",
"players":"sd:player:6897db83-b25f-4c54-832a-0ff0c3cb86ff,sd:player:481ffe40-392b-4a1b-89ec-0d9453495639,sd:player:681d2cc6-24b9-4f38-8564-8c0b210a9535,sd:player:c468bdc9-4778-496a-985e-7911dc6a1ff2,sd:player:ed56bced-c614-4eeb-85ee-812edb594752,sd:player:1d0c6b20-76b7-4a82-ae1d-20b78136525b,sd:player:34736ed7-c86a-472c-8c1c-683002de6487,sd:player:92f6b357-f6cb-40a5-8893-329425fff5ba,sd:player:ec3df621-2a9d-483c-9064-11b44d8841a9,sd:player:8869c334-f08c-4ed9-931c-9d9c657cb7bc",
"event_type":"rebound",
"event_category":"shot",
"locale":"en",
"operation":"update",
"version":"v7"
}
}
{
"heartbeat":{
"interval":5000
}
}
you can use interval to get the data from API and then passing the data to websocket server
Use eventsource if this event is triggered by your API.
https://developer.mozilla.org/en-US/docs/Web/API/EventSource
Otherwise websocket is much better, than setInterval.

how to convert json to csv in react using map

I have convert the json data into csv on button click but what actually happen that they are storing in csv file in ,(comma) but I want them to be a separated in lines. How can I do that
Example = Minor,Minor But I Want them in separate Line.
Here is my code and Image.
This is csv file where minor minor and id in same line I want to separate them in other line
const apiForId = async() =>{
console.log("The value of isCheck", isCheck)
await axios.post(`${process.env.REACT_APP_API_UfL}/export/packs/`,isCheck
)
.then((res) => {
console.log(res)
setValue(res.data)
})
}
// Here download DataA
const downloadData = async(e) =>{
await apiForId()
down.current.click();
}
const data = value.map(item=>({
_id:item._id,
_id_sound:item.pack_sounds_ids.map(data=>data._id),
pack_name:item.pack_name,
chord_att_value:item.pack_sounds_ids.map(data=>data.chord_type_id.att_value),
instrumendts_att_value:item.pack_sounds_ids.map(data=>data.instruments_ids.map(ele => ele.att_value)),
key_att_value:item.pack_sounds_ids.map(item=>item.key_id.att_value),
maininstrument_att_value:item.pack_sounds_ids.map(item=>item.maininstrument_id.att_value),
product_att_value:item.pack_sounds_ids.map(item=>item.product_type_id.att_value),
refrence_att_value:item.pack_sounds_ids.map(item=>item.references_ids.map(ele=>ele.att_value)),
root_att_value:item.pack_sounds_ids.map(item=>item.root_note_id.att_value),
sound_bpm:item.pack_sounds_ids.map(item=>item.sound_bpm),
sound_index:item.pack_sounds_ids.map(item=>item.sound_index),
sound_name:item.pack_sounds_ids.map(item=>item.sound_name),
tags_att_value:item.pack_sounds_ids.map(item=>item.tags_ids.map(ele=>ele.att_value))
}))
const headers = [
{
label:"Pack ID",
key:"_id",
},
{
label:"Sound ID",
key:"_id_sound",
},
{
label:"Pack Name",
key:"pack_name",
},
{
label:"Chord",
key:"chord_att_value",
},
{
label:"Instruments",
key:"instrumendts_att_value",
},
{
label:"Key",
key:"key_att_value",
},
{
label:"Maininstrument",
key:"maininstrument_att_value",
},
{
label:"Product Type",
key:"product_att_value",
},
{
label:"Refrences",
key:"refrence_att_value",
},
{
label:"Root Note",
key:"root_att_value",
},
{
label:"BPM",
key:"sound_bpm",
},
{
label:"Index",
key:"sound_index",
},
{
label:"Name",
key:"sound_name",
},
{
label:"Tags",
key:"tags_att_value",
},
]
//BUTTON
<Button className="mx-5" onClick={downloadData}> Download CSV</Button>
<CSVLink headers={headers} data={data}><span ref={down}></span></CSVLink>
use this module https://www.npmjs.com/package/json2csv and using option unwind you can make it as 1 to many rows.
Details :
--unwind [paths]
Creates multiple rows from a single JSON document similar to MongoDB unwind.
--unwind-blank
When unwinding, blank out instead of repeating data. Defaults to false. (default: false)

Jquery Vegas Plugin overlay not working

I am using the plugin off of http://vegas.jaysalvat.com/documentation/slideshow/
The backgrounds are changing fine, but the overlay image is not working or rendering.
Here is my code I have in the head of the page:
<script>
$.vegas('slideshow', {
backgrounds:
[
{ src:'/../../images/backdrop.png' },
{ src:'/../../images/backdrop_yellow_trees.png' },
{ src:'/../../images/backdrop.png' }
]
})('overlay', {
src:'/../../assets/vegas/overlays/13.png'
});
</script>
Same problem here, but based on the #pawel reply over I came to this
$(function() {
$.vegas('slideshow', {
backgrounds:[
{ src:'images/pic1.jpg', fade:800 },
{ src:'images/pic2.jpg', fade:800 },
{ src:'images/pic3.jpg', fade:800 },
{ src:'images/pic4.jpg', fade:800 }
]
})('overlay', {
src:'vegas/overlays/15.png'
});
});
We probably made the same mistake, just copy paste from the documentation...

jQuery ui autocomplete usin JSON file

I am having some trouble getting autocomplete to work specifically with a json file. It
giving following error whenever something is entered in the text box
url is undefined
following is my jQuery code
$(document).ready(function() {
$('#autocomplete').autocomplete({
minChars: 1,
source: function(request, response) {
var url='dataa.json';
$.getJSON(url,{term: request.term},function(data){
response($.map(data.ledgers, function(item) {
return item.value;
}));
})
}
});
});
and the JSON
{
"ledgers":
[
{
"id":"2001",
"name":"Bharat"
},
{
"id":"2003",
"name":"Gaurav"
},
{
"id":"2002",
"name":"Pankaj"
},
{
"id":"2022",
"name":"Purchase"
},
{
"id":"2007",
"name":"Ram"
},
{
"id":"2008",
"name":"Ramesh"
},
{
"id":"2009",
"name":"Suresh"
}
]}
Your JSON file format needs to contain value or label (or both). Change name to value and it should work fine.
$('#autocomplete').autocomplete({
minChars: 1,
source: function(request, response) {
var url='dataa.json';
$.getJSON(url,{term: request.term},function(data){
response($.map(data.ledgers, function (value, key) {
return {
label: value,
value: key
};
}));
})
}
});
Try adding 'use strict'; at the top of your $(document).ready(). That may point out what the problem is...
return item.value;
item does not have a value, try returning id or name, which it does have.

Categories

Resources