How to make html_url into hyperlinks from fetch/json - json

I am learning javascript and Json so please bear with me.
I have fetched certain json data and made it visible on my webpage. All this through my GitHub api. I have three repositories in total and each contain the name of the repository a description and a html_url. I would like to make the three html_url active. So the user can click directly on them and go to that repository. I've been trying and googling but have yet to have any success. Any tips would be hugely appreciated.
Below is my js code.
`
function load () {
element = document.getElementById("gitRepos");
element.classList.toggle("hide");
const loadingStatus = document.querySelector('#gitRepos')
let url = "https://api.github.com/users/PaulEvans78/repos"
async function getrepo() {
let response = await fetch(url);
const repoList = document.getElementById("gitRepos")
const links = document.getElementById("gitRepos")
if(response.ok) {
let data = await response.json();
loadingStatus.innerText = " "
console.log(data);
for (const item of data){
createRepoLi(repoList, item.name, item.html_url, item.description)
}
} else {
console.log("HTTP-Error: " + response.status);
}
}
function createRepoLi(repoList, name, html_url, description){
const li = document.createElement('li')
li.innerText = name + "\n " + html_url + "\n " + description
li.classList.add("gitHubStyle");
repoList.appendChild(li)
}
getrepo();
}
`

Related

Res.Json returns duplicated array

I'm using react js with express as backend and mysql.
When i'm trying to show the data from the database with the next query I notice in the console of the browser that res.json returns two arrays
This is the code to get the data
export const allVehiculos = async (req,res) => {
try {
var query= "SELECT `idVehiculos`, `placa`, `codip`, `descp`, `anio`, `clase`, `color`, `motor`, `serie`, `marca` " +
"FROM vehiculos AS vehiculos " +
"INNER JOIN marcas as marcas " +
"on `Vehiculos`.`idMarca` = `marcas`.`id`"
const vehiculos = await db.query(query)
res.json(vehiculos)
} catch (error) {
res.json({message: error.message})
}
}
This is the code of the react component
const [vehiculos, setVehiculo] = useState([])
useEffect( () => {
getVehiculos();
}, [])
return(
vehiculos.map((item) => {
return(
<tr key={item.idVehiculos} className="table-row row-item">
<td>{item.placa}</td>
<td>{item.codip}</td>
<td>{item.descp}</td>
<td>{item.anio}</td>
<td>{item.clase}</td>
<td>{item.color}</td>
<td>{item.motor}</td>
<td>{item.serie}</td>
<td>{item.marca}</td>
</tr>
)})
)
Result of res.json
Info not showing
But, when I change
res.json(vehiculos)
to
res.json(vehiculos[0])
Then i got just one array and the information shows correctly
Info showing correctly
I don't know why res.json returns two arrays and how to get only one array
Sorry for my bad english,
I'm very new in this field.
Thanks.

How to add multiple files from server response to zip file in Angular

exportIcsReportInJSONFormat() {
this.icsService.getICSReport()
.pipe(takeUntil(this.notifier))
.subscribe(response =>{
const icsReport =new Blob([response], { type: 'text/json;charset=utf-8' });
saveAs(icsReport, 'ics-report_' + new Date().toISOString() + '.json')}
);
}
exportIcsReportInCSVFormat() {
this.icsService.getICSReport()
.subscribe(
response => {
const csv = this.convertJSONToCSV(response);
const csvBlob = new Blob([csv], { type: 'text/json;charset=utf-8' });
saveAs(csvBlob, 'ics-report_' + new Date().toISOString() + '.csv');
});
}
exportIcsReportInTSEFormat() {
this.icsService.getTse()
.pipe(takeUntil(this.notifier))
.subscribe(tse => saveAs(tse, 'ics-report_' + new Date().toISOString() + '.tse'));
}
Calling the functions here to generate the files and adding them to zip:
getReports() {
const zip: JSZip = new JSZip();
this.selectedReportFormats.forEach(element => {
if (element == 'JSON') {
const JSONFile = this.exportIcsReportInJSONFormat();
zip.file("JSONFile");
}
if (element == 'CSV') {
const CSVFile = this.exportIcsReportInCSVFormat();
zip.file("CSVFile");
}
if (element == 'TSE') {
const TESFile = this.exportIcsReportInTSEFormat();
zip.file("TESFile");
}
zip.generateAsync({type:"blob"})
.then(function(content) {
// see FileSaver.js
saveAs(content, "example.zip");
});
});
}
I am doing it wrong because I can't find proper syntax to add files to zip kind of using a loop. This scenario is basically I want to download a report and I have 3 options JSON, CSV and TSE. So I have a checkbox and the options I check and click on Download I get files in all those formats added to zip and downloaded in a ZIP file.

Invalid Json Response when accessing third-party service with Wix Corvid

I am attempting to gather details about real estate properties through an external API. I've gone over their documentation relentlessly but can not figure out why I am receiving the following error:
invalid json response body at https://api.gateway.attomdata.com/propertyapi/v1.0.0/property/expandedprofile?address1=34%20Karen%20Court&address2=Bridgeport20%CT reason: Unexpected token < in JSON at position
For reference, I am posting my code. If anyone can provide any input or guidance I would greatly appreciate it!
Backend Code:
import { fetch } from 'wix-fetch';
import { wixData } from 'wix-data';
export function getDetails(address, citystatezip) {
const url = 'https://api.gateway.attomdata.com/propertyapi/v1.0.0/property/expandedprofile?address1=' + address + "&address2=" + citystatezip;
let headers = {
"apikey": "xxxxxxxx",
"accept": "application/json"
};
let options = {
headers: headers
}
console.log("Url: " + url);
return fetch(url, { method: 'get' })
.then(response => {
return response.json();
})
.then((data) => {
console.log(data);
return data;
});
}
Page Code:
wixWindow.getCurrentGeolocation()
.then((obj) => {
let timestamp = obj.timestamp; // 1495027186984
let latitude = obj.coords.latitude; // 32.0971036
let longitude = obj.coords.longitude; // 34.774391099999995
let altitude = obj.coords.altitude; // null
let accuracy = obj.coords.accuracy; // 29
let altAccuracy = obj.coords.altitudeAccuracy; // null
let heading = obj.coords.heading; // null
let speed = obj.coords.speed;
console.log(obj)
reverse(latitude, longitude)
.then(geocode => {
console.log(geocode)
let id = geocode.results[0].place_id;
details(id)
.then(detailed => {
console.log(detailed)
$w("#input12").value = geocode.results[0].address_components[0].long_name + " " + geocode.results[0].address_components[1].long_name;
$w("#input10").value = geocode.results[0].address_components[3].long_name;
$w("#input11").value = geocode.results[0].address_components[5].long_name;
$w("#text37").text = geocode.results[0].formatted_address;
$w("#googleMaps2").location = {
"latitude": latitude,
"longitude": longitude,
"description": geocode.results[0].formatted_address
};
let address = geocode.results[0].address_components[0].long_name + " " + geocode.results[0].address_components[1].long_name;
let city = geocode.results[0].address_components[3].long_name;
let state = geocode.results[0].address_components[5].short_name;
let citystate = city +"%2C" + "%20" + state;
console.log(citystate)
const uri = address;
const encoded = encodeURI(uri);
console.log(encoded);
getDetails(encoded, citystate)
.then(got => {
console.log(got)
})
});
});
Thank you in advance for any input or guidance you can offer. I have spent hours trying to figure this out to no avail.
Stay safe and stay well 😊

Unable to change the value of Filtered data length in angular4

I want to change the count of the filterdata [i.e. [(ngModel)]="filterdata"] after the data has arrived in the tables. For Example:
Initially in the text-box, i entered "experia" so all the data from the database that has experia appeared in the table. And the number of data is displayed on the right-hand of the table as you can see in the picture => "Number of searched data = 6". However, the issue is, if i enter text again in the search-text box and the data filters, but this filtered data number is not displayed, like "Number of searched data =4", of course this number will be less than the maximum number i.e.=6.It remains the same as >> "Number of searched data = 6" even though the total data displayed number is 4.
I have used an (ngModelChange) because i thought it might work, but it doesn't.
code:
transaction.component.html
<input class="form-control" id="input1-group1" style="margin-
top:20px" type="text" name="search" placeholder="Enter Search Text"
[(ngModel)]="filterdata" (ngModelChange)=
"countFilter(filterdata)"(keyup.enter)="searchByText(filterdata)">
//code
<h2> Transaction </h2>
<label *ngIf="toShowCount" id="arrayCountId"> Number of searched
data : {{arrayCount}}</label>
transaction.component.ts
countFilter(filtData){
console.log("inside countFilter = "+ filtData)
this.countFilterData = filtData.length;
if(this.arrayCount>=0){
if(this.countFilterData<this.arrayCount){
var result = [];
var url = config.url;
var port = config.port;
this.http.post("http://" + url + ":" + port +
"/transaction/masterSearchTransactionForm/", this.filterObj
, { headers: new Headers({ 'Authorization': 'Bearer ' +
localStorage.getItem('Token') }) })
.map(result => this.result = result.json())
.subscribe((res: Response) => {
console.log("# DATE FILTER RESULT TRANSACTION XXXXXXXXXXXX",
res);
this.records = res;
this.toShowCount =true;
console.log ("the result of SearchByText is = ", this.result)
this.arrayCount = this.result.length;
console.log("ArrayCount = " , this.arrayCount)
console.log("search-by-text records = ",res)
console.log("Search by Text result is : " + result)
if (this.result.length > 0) {
this.notify.Success("Data Displayed Successfully");
this.loading = false;
}
else {
this.notify.Error("No Matching Data Available")
this.loading = false;
}
});
}
}
You don't need (ngModelChange)="countFilter(filterdata)" because as i can see you have 2 methods that call REST endpoint for filtering data: one in countFilter(filterdata) and the other one in searchByText(filterdata). When you call searchByText(filterdata) i presume that you are trying to filter data on server and get results. When you get that result from server, than you put length of that result in variable like you did in countFilter method.
this.arrayCount = this.result.length;
just put this in searchByText method and remove countFilter because you do not need it.
EDIT:
<input class="form-control" id="input1-group1" style="margin-
top:20px" type="text" name="search" placeholder="Enter Search Text"
#searchControl (keyup.enter)="searchByText(searchControl.value)"
(input)="countFilter($event.target.value)"
>
in your .ts file you will have a method searchByText(value) that calls API endpoint and query data table, something like this:
searchByText(value) {
this.http.post("http://" + url + ":" + port +
"/transaction/masterSearchTransactionForm/", this.filterObj
, { headers: new Headers({ 'Authorization': 'Bearer ' +
localStorage.getItem('Token') }) })
.map(result => this.result = result.json())
.subscribe((res: Response) => {
this.records = res;
}
Now , you have saved all data that you queried first time with ENTER click
After this you want to have method that can filter through this saved data:
countFilter(value) {
this.records = this.records.filter((record) => record.name == value);
}
now you have a same variable (this.records) with filtered data! And in html you can just do string interpolation {{this.records.length}}

Extract Value from Json string in Ionic 2

I am using OAuth2 for authorization in my Ionic 2 App and the decoded token response(which I am getting from the BASE64.decode() function) is like the below(key-value form).I am storing it in a variable called 'tokendata' of type 'any'. Now I want to extract values from this decoded token. Now if I simply do 'tokendata.personnelnbr', it is not working. Also if I do a 'json.parse(tokendata) or a json.parse('tokendata'), store it in another variable say 'myVar' and then try to access 'myVar.personnelnbr', then also it is not working. Please help with the solution!
{
"client_id":"xxx",
"scope":"user_profile",
"sub":"yyy",
"amr":"external",
"auth_time":1499753830,
"idp":"eso_enterprise",
"upn":"yyy",
"email":"yyy",
"samaccount_name":"yyy",
"peoplekey":"1169",
"personnelnbr":"1108",
"given_name":"Deblina",
"sn":"Dutta Chowdhury",
"exp":1499,
"nbf":1499
}
The method where I am trying to access the 'personnelnbr' field is given below:
private initializeApp(): void
{
this.platform.ready().then(() => {
console.log("Before login Deblina");
/**
* Read in app configuration, get an oAuthV1 ESO token, register device with REBAR Notification Services
*/
this.configService.Initialize().subscribe(
() => this.esoService.getV2Token().subscribe(
(v2Token) => {
this.tokendata = BASE64.decode(v2Token);
alert("Token Deblina decoded: " + BASE64.decode(v2Token));
console.log("Token Deblina decoded: " + BASE64.decode(v2Token));
this.concatenatedToken = "'" +this.tokendata+ "'";
alert(this.concatenatedToken);
console.log(this.concatenatedToken);
this.myVar = JSON.parse(this.tokendata);
alert("Now:" + this.myVar.personnelnbr);
console.log("Now:" + this.myVar.personnelnbr);
this.myVar = JSON.parse(this.concatenatedToken);
alert("Now:" + this.myVar.personnelnbr);
console.log("Now:" + this.myVar.personnelnbr);
},
(error) => console.log(error),
() => { this.nav.setRoot(HomePage)}
),
(error) => console.log(error)
);
});
}
If you just want to to extract value, you can do this:
let datas = {
"client_id":"xxx",
"scope":"user_profile",
"sub":"yyy",
"amr":"external",
"auth_time":1499753830,
"idp":"eso_enterprise",
"upn":"yyy",
"email":"yyy",
"samaccount_name":"yyy",
"peoplekey":"1169",
"personnelnbr":"1108",
"given_name":"Deblina",
"sn":"Dutta Chowdhury",
"exp":1499,
"nbf":1499
};
for (let key in datas) {
console.log(key + " => " + datas[key]);
}