Read API response in Angular2 & ionic - javascript

I have successfully get it work to request data from API with http.get in Angular2. This is my http.get
this.http.get('http://localhost:8001/v1/recent', {
headers: headers
})
.map(res => res.text())
.subscribe(
data => console.log(data.total),
() => console.log('API request complete')
);
The API is based on Laravel, it will return data as follows
{
"total": 8,
"per_page": 50,
"current_page": 1,
"last_page": 1,
"next_page_url": null,
"prev_page_url": null,
"from": 1,
"to": 8,
"data": [
{
"id": 1,
"name": "John Doe",
"author": {
"isBlocked": "0",
}
},
{
"id": 1,
"name": "John Doe",
"author": {
"isBlocked": "0",
}
}
]
}
How can I retrieve the JSON object above in Angular2? and all of it's nested array?
console.log(data.total) above is return undefined

The json in your question is not properly formatted, you have an extra comma after "isBlocked":"0" (in line 15 and in line 22)
"author": {
"isBlocked": "0",
}
which will make it a invalid JSON. Preventing Angular from parsing it correctly.
The other issue, you are calling .map(res => res.text()) which will convert your response body to a string not an object. If you want it as a javascript object do .map(res => res.json()) instead.
Here is a working plunker

Related

How to create a variable from response body in Postman?

I have the following response body:
`
{
"timestamp": "2022-11-08T12:40:11.631Z",
"data": {
"version": "2.2",
"endpoints": [
{
"identifier": "credentials",
"role": "SENDER",
"url": "https://example.com/credentials65"
},
{
"identifier": "tokens",
"role": "RECEIVER",
"url": "https://example.com/tokens245"
},
{
"identifier": "tokens",
"role": "SENDER",
"url": "https://example.com/tokens353"
},
.......
For each identifier and role (in Postman tests session), i want to define variables automatically.
I tried the following for the first ones:
_.each(pm.response.json(), (responseBody) => {
if (responseBody.identifier['data'][1]['identifier'] === "credentials") {
pm.globals.set("credentials_url", responseBody.url)
}
else if (responseBody.identifier === "tariffs") {
pm.globals.set("tariffs_url", responseBody.url)
}
})
The problem is that i do not know how to call the "identifier" and the script do not enter in the if loop. Can anyone help?
const endpoints = pm.response.json().data.endpoints;
for (const endpoint of endpoints) {
const array = pm.globals.get(`${endpoint.identifier}_url`) ?? [];
array.push(endpoint.url);
pm.globals.set(`${endpoint.identifier}_url`, array);
}
You can access the URLs in the arrays by using pm.globals.get("tariffs_url"), pm.globals.get("credentials_url") etc. (it'll work for every identifier)

Remove JSON row columns without looping

I have an API that returns JSON data. But now I want to remove some of the data without looping through the entire object.
The sample JSON data is:
[
{
"cost":"KES 0.8000",
"messageId":"ATXid_0fae395279b54d51519de5581230a7e8",
"messageParts":1,
"number":"+2547112xxxxxx",
"status":"Success",
"statusCode":101
},
{
"cost":"KES 0.8000",
"messageId":"ATXid_19a0a09efcf39e87245a57f6403631d5",
"messageParts":1,
"number":"+2547112xxxxxx",
"status":"Success",
"statusCode":101
},
{
"cost":"0",
"messageId":"None",
"number":"+25470000000000",
"status":"InvalidPhoneNumber",
"statusCode":403
}
]
I want to extract only data like:
[
{
"number":"+2547112xxxxxx",
"status":"Success"
},
{
"number":"+2547112xxxxxx",
"status":"Success"
},
{
"number":"+25470000000000",
"status":"InvalidPhoneNumber"
}
]
I am working using Node.js with express framework.
In simple ways, using the .map() function, you can do something like this:
console.log(arr.map(({number, status}) => ({
number,
status
})));
Full Snippet
const arr = [{
"cost": "KES 0.8000",
"messageId": "ATXid_0fae395279b54d51519de5581230a7e8",
"messageParts": 1,
"number": "+2547112xxxxxx",
"status": "Success",
"statusCode": 101
},
{
"cost": "KES 0.8000",
"messageId": "ATXid_19a0a09efcf39e87245a57f6403631d5",
"messageParts": 1,
"number": "+2547112xxxxxx",
"status": "Success",
"statusCode": 101
},
{
"cost": "0",
"messageId": "None",
"number": "+25470000000000",
"status": "InvalidPhoneNumber",
"statusCode": 403
}
];
console.log(arr.map(({number, status}) => ({
number,
status
})));

Javascript + JQuery: Object properties are undefined [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
I'm trying to build a simple web app using JQuery. I'm trying to make an ajax request to the server the following way:
function getClients() {
return $.ajax('/api/v1/clients',
{
headers: {
Authorization: 'Token ' + getCookie("auth_token")
}
});
}
I also do the following:
$(document).ready(function() {
console.log(getClients());
});
So that I can see the result of my request. In the console I see the following:
{
"readyState": 4,
"responseText": "{\"count\":2,\"next\":null,\"previous\":null,\"results\":[{\"id\":2,\"group_set\":[1],\"first_name\":\"b\",\"last_name\":\"b\",\"username\":\"b\",\"telegram_id\":null,\"phone\":null,\"picture\":null,\"blocked\":false,\"telegram_user\":null,\"user\":2,\"source\":null},{\"id\":1,\"group_set\":[1],\"first_name\":\"a\",\"last_name\":\"a\",\"username\":\"a\",\"telegram_id\":null,\"phone\":null,\"picture\":null,\"blocked\":false,\"telegram_user\":null,\"user\":2,\"source\":null}]}",
"responseJSON": {
"count": 2,
"next": null,
"previous": null,
"results": [
{
"id": 2,
"group_set": [
1
],
"first_name": "b",
"last_name": "b",
"username": "b",
"telegram_id": null,
"phone": null,
"picture": null,
"blocked": false,
"telegram_user": null,
"user": 2,
"source": null
},
{
"id": 1,
"group_set": [
1
],
"first_name": "a",
"last_name": "a",
"username": "a",
"telegram_id": null,
"phone": null,
"picture": null,
"blocked": false,
"telegram_user": null,
"user": 2,
"source": null
}
]
},
"status": 200,
"statusText": "OK"
}
(This output is made by clicking on "Copy object" in Firefox).
However, if I change getClients() as shown below:
function getClients() {
return $.ajax('/api/v1/clients',
{
headers: {
Authorization: 'Token ' + getCookie("auth_token")
}
}).responseJSON;
}
Then in the console I will get
undefined
Also, when I try to use the object's properties in code, I get an error that the properties are undefined.
How is that and how do I fix this?
Thank you.
getClients returns promise. Your code:
return $.ajax(...).responseJSON
reads responseJSON from promise object which is undefined. Promise returns result only when it is resolved (then())
You should leave getClients as is and change part in document ready like:
$(document).ready(function() {
getClients().then(function(response) {
const respJson = JSON.parse(response);
console.log(respJson.responseJSON);
});
})
Keep the getClients() function as seen below:
function getClients() {
return $.ajax('/api/v1/clients',
{
headers: {
Authorization: 'Token ' + getCookie("auth_token")
}
});
}
Then use Bracket Notation to select properties:
var clientData = getClients();
var jsonData = clientData["responseJSON"];
var results = jsonData["results"];
console.log(results[0]["first_name"]); // Logs the "first_name" value from first results array
Since your JSON properties are strings, Bracket Notation is required. Otherwise, you could use, for example: clientData.responseJSON

calling firebase inside an forEach makes the iteration not work

Goal:
Im trying to make an array of objetcs including 3 informations: id, title and imageUri. But when i try to get the imageUri value from firebase(an image download URL from firebase) to download this image in another component, the iteration of forEach freezes. Thank you for your time :)
Warning:[Unhandled promise rejection: TypeError: JSON.stringify cannot serialize cyclic structures.]
observation: When i remove the firebase part imageUri: firebase..., the whole thing works!
the function:
processData = ( data ) => {
console.log('---------data received from loadData(Main.js:70)--------\n', data)
var localProcessedData = [];
Object.entries(data).forEach( ([key, value]) => {
var event = {
id: key,
title: Object.getOwnPropertyDescriptor(value, "eventTitle").value,
imageUri: firebase.storage().ref('events/active/' + key + '/image').getDownloadURL()
}
localProcessedData.push(event);
})
this.setState({
processedData: localProcessedData,
eventsDataIsLoaded: true,
})
}
The type of params the function recieve:
Object {
"-M-I83aV9t1fezOsBn17": Object {
"active": true,
"created": "2020-02-05T02:18:30.772Z",
"description": "Olimpiadas Inter Atletica",
"eventTitle": "oia",
"location": "Uberlandia",
"owner": "p87xn6x8DZTwb6qyTadhkk3UxJV2",
"price": "130",
"startDate": "15",
"time": "14",
"updated": "2020-02-05T02:18:30.772Z",
},
"-M-KlUH-zQhnIhb6wMH8": Object {
"active": true,
"created": "2020-02-05T14:34:20.399Z",
"description": "Cia 2020",
"eventTitle": "Cia",
"location": "Uberlandia",
"owner": "p87xn6x8DZTwb6qyTadhkk3UxJV2",
"price": "130340",
"startDate": "15",
"time": "14",
"updated": "2020-02-05T14:34:20.399Z",
}
}
Expected:
My goal is to transform that whole data in an array like this:
Array [
Object {
"id": "-M-I83aV9t1fezOsBn17",
"title": "oia",
"imageUri": "image url from firebase"
},
Object {
"id": "-M-KlUH-zQhnIhb6wMH8",
"title": "Cia",
"imageUri": "image url from firebase"
}
]
Based on firebase documentation. FIrebase Storage getDownloadUrl is a promise
https://firebase.google.com/docs/reference/js/firebase.storage.Reference.html#get-downloadurl
solution is to implement an async/await
async processData = ( data ) => {
console.log('---------data received from loadData(Main.js:70)--------\n', data)
var localProcessedData = [];
Object.entries(data).forEach( async([key, value]) => {
var event = {
id: key,
title: Object.getOwnPropertyDescriptor(value, "eventTitle").value,
imageUri: await firebase.storage().ref('events/active/' + key + '/image').getDownloadURL()
}
localProcessedData.push(event);
})
this.setState({
processedData: localProcessedData,
eventsDataIsLoaded: true,
})
}
this code is not yet tested.

sort the Json data According to timestamp in Vuejs

I am rending a Json using api
new window.Vue({
el: '#containerwrapper',
data() {
return {
bannerData:""
}
},
created() {
axios.get('http://localhost:8080/pi.json')
.then(response => {
this.bannerData = response.data;
});
},
})
This gives me the Json data as follows
[
{
"id": 118,
"title": "Feuerwerk",
"location": "MUC",
"pressInformation": [
{
"id": 215,
"tstamp": "1577110478",
"created": "2019-09-10T12:13:53+02:00",
"title": "Chemi215",
"teaser": "",
"subline": "Ursachenforschung dauert"
}
]
},
{
"id": 144,
"title": "Testing Stage",
"location": "BER",
"pressInformation": [
{
"id": 254,
"tstamp": "1576838212",
"created": "2019-11-27T13:47:31+01:00",
"title": "Chemi254",
"teaser": "",
"subline": ""
},
{
"id": 250,
"tstamp": "1576838221",
"created": "2019-12-09T12:36:36+01:00",
"title": "Chemi250",
"teaser": "",
"subline": ""
}
]
}
]
I render the data in my template as follows
<div v-for="(eventTitle, i) in bannerData">
<div v-for="(title,index) in eventTitle.pressInformation" :key="title.id">
<div id="pressTimeStamp">{{title.created}} Uhr</div>
<div id="pressTitleTitle">{{title.title}}</div>
<div id="pressTitle">
<h2>{{eventTitle.title}}</h2>
<div id="pressSubline">{{title.subline}}</div>
</div>
</div>
And the output is coming as i expected. Can someone suggest me, how to write a method so my output would be sorted out depends on the 'created' timestamp
new window.Vue({
el: '#containerwrapper',
data() {
return {
bannerData:""
}
},
created() {
axios.get('http://localhost:8080/pi.json')
.then(response => {
response.data.pressInformation.sort(function(a, b){return b['tstamp']-a['tstamp']}));
this.bannerData = response.data;
});
},
})
You can use the sort method with a callback function.
From your data it seems that you already have the timestamp in seconds. It is easy so sort using that.
For example you can write something like this:
arr.sort(function(a, b) {
return +a.pressInformation.tstamp - +b.pressInformation.tstamp;
});
If you are writing a-b denotes ascending order, while b-a is descending order.
The extra + signs are used here to convert from string to int.
Docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

Categories

Resources