Cannot output array from http get url success function onto the html - angularjs

I am trying to output the result from the success function as following, but am having no luck. The code does return values for UpcomingEvents and if I output that to the html, it works, but when I am passing it onto the returnlist, it does not work.
$scope.Events = {}
$scope.returnlist = {};
var PriorID = 67;
var i = 0;
var j = 0;
//I am calling http get url function which is working fine.
.success(function (response) {
console.log(response);
$scope.Events = response;
//I am able to display Events[0].ID in html.
if ($scope.Events[0].ID == PriorID)
//The condition holds true, so it will go inside the loop. I have
confirmed that with a debugger.
{
newID = $scope.Events[0].ID;
newname = $scope.Events[0].Title;
$scope.returnlist[0] = [{ ID: newID, Name: newname }];
$scope.returnlist[1] = [{ ID: newID, Name: newname }];
//through debugger breakpoints, I have found that returnlist is
getting the correct values.
}
})
Everything works well until I try to display the values in my html. I am trying it like this.
{{returnlist[0].ID}}
I have even tried it like this:
<tr ng-repeat="data in returnlist">
<td>returnlist.ID</td>
but no luck. What am I doing wrong?
Thanks.

first you define $scope.returnlist = {}; which is an object not an array.
Then, when you add item you assign an array not an item of array:
$scope.returnlist[0] = [{ ID: newID, Name: newname }];
So your final returnlist will look like:
{0: [{ ID: newID, Name: newname }], 1:[{ ID: newID, Name: newname }],...}
an object with array value, so when you do $scope.returnlist[0].ID you will get undefined.
The right way is:
$scope.returnlist = [];//an array
//in the loop now:
$scope.returnlist[0] = { ID: newID, Name: newname };//an item not an array

Related

Insert list data over the iteration(map)

Here I am trying to modify my data over the iteration and send some result to API call.
The API Call receives a request with a structured data format which is
{ list: [{ id: "1", name: "Hello" }, ... ] }
Somehow I managed to call the API with single data ( const params in my current code, it only accepts single data).
But now it has to be done with multiple data something like this:
{ list: [{ id: "1", name: "Hello" }, { id: "22", name: "Ed" }, { id: "36", name: "Jason" } ... ] }
Here is my current code
const [table, setTalbe] = useState(..); // assume, we have some table data here
const processNow = () => {
let id = 0;
let name = '';
// if table length is greater than 1, we go for the loop.
if (table.length >= 1) {
table.map(data => {
id = data.userId;
name = data.userName;
});
//insert table data to params, here I want to add whole table data into "list"
//the final result of this list should be something like this
//ex ) list: [{ id: '123', name: 'Josh' }, { id: '125', name: 'Sue' }, { id: '2222', name: 'Paker' } ...],
// but how??
const params: any = {
list: [
{
id: id,
name: name
},
],
};
//send PUT reqeust with params
axios
.put(
'/api/v1/tosent',
params,
)
.then(res => {
console.log('The response', res);
})
.catch(err => {
console.log('The error: ', err);
});
}
};
but I'm stuck with it, please help me to finish this code to work properly.
need your kind advice.
Array.prototype.map returns a new array with the function you pass applied to every element. You should study the MDN documentation on map to understand its use.
Your current code does nothing with the map return value:
table.map(data => {
id = data.userId;
name = data.userName;
});
You probably assumed .map would mutate the data, as in change it in place. Instead, the whole operation returns a new array.
It looks like you want to do:
const list = table.map(data => {
return {
id: data.userId,
name: data.userName
}
});
This is applying a function to every element in the array that will map each element to a new object, matching your question, with an id and name key. Then it looks like you want to pass the returned value of map (which we named list above) to your call:
const params: any = {
list: list
};

How to get values in [object Object] in to an Array or how can i access those values in Angular

This is my Angular Code which i have written in component.ts file.I am getting data from backend API and try to console.log and see the data.
getInfo() {
const params = [];
params.push({code: 'Code', name: 'ty_PSD'});
params.push({code: 'continentCodes', name: ['CAN']});
params.push({code: 'dateFrom', name: '2019-01-01'});
params.push({code: 'dateTo', name: '2019-12-31'});
params.push({code: 'statusType', name: 'REAL'});
params.push({code: 'valueType', name: 'TTV'});
this.serviceHandler.getDemand([], params).subscribe(
demand => {
console.log(demand + 'ddd');
});
}
But in here console.log(demand + 'ddd'); api response is shown like this.
This is my console.log(demand) output.
How could i get values in data: Array(365) values in to an array.
You should not concatenate/sum an object with a string because console.log parses the object as a string.
I think you want the number 4 in the examples bellow: console.log(JSON.stringify(obj) + 'aaa');
var obj = { a: 'aa', b: 0, c: true};
console.log(1, obj + 'aaa');
console.log(2, obj);
console.log(3, JSON.stringify(obj));
console.log(4, JSON.stringify(obj) + 'aaa');
The API response is in string format. You need to parse it.
Try:
console.log(JSON.parse(demand))

Adding property in array. Add the last value in all array

"I'm adding a property on array while in a forEach loop. But when I do the console.log() the added value on each array is always the last value of the foreach loop."
deliveries data has location and I want to pass the location to pickupDetails.
deliveries: [{ //data of deliveries that I want to pass in pickupDetails
0: {Location: Korea},
1: {Location: Japan}
}]
let pickupDetails = this.state.pickupDetails;
//pickupDetails is only one object then It will become two since the deliveries has 2 objects
pickupDetails = {
name: "June"
}
this.state.deliveries.forEach((delivery, index) => {
pickupDetails.location = delivery.location;
console.log(pickupDetails)
})
the result of the console:
pickupDetails = {
name: "June"
location: "Japan" //this should be Korea since the first loop data is korea
}
pickupDetails = {
name: "June"
index: "Japan"
}
I think something missing from that code maybe because its dummy data. alright from my point of view you confused with javascript reference.
deliveries: [{ //data of deliveries that I want to pass in pickupDetails
0: {Location: Korea},
1: {Location: Japan}
}]
let pickupDetails = this.state.pickupDetails;
this.state.deliveries.forEach((delivery, index) => {
let newPickupDetails = JSON.parse(JSON.stringify(pickupDetails));
newPickupDetails.location = delivery.location;
console.log(newPickupDetails);
})
the result of the console:
pickupDetails = {
name: "Juan"
location: "Japan" //this should be Korea since the first loop data is korea
}
pickupDetails = {
name: "June"
index: "Japan"
}
JSON.parse and JSON.stringify we use for create new object instead of use reference. console log effected because it linked by reference so if you make it new object it will do.
Check variable newPickupDetails

Elasticsearch query parse failure

Why does this ES multi-match query return a 400 error (bad request)?
"query": {
"multi_match": {
"query": searchTerms,
"fields": ["content", "title"],
"operator": "and"
}
},
size: 100,
from: 0,
highlight: {
fields: {
"title": {number_of_fragments: 0},
"content": {number_of_fragments: 10,fragment_size: 300}
}
}
}
I'm using this query in conjunction with AngularJS UI Bootstrap Typeahead code like this
uib-typeahead="query as query._source.ymme for query in getSuggestions($viewValue)" typeahead-on-select="search($item)"
This is my search() function
$scope.search = function() {
console.log($scope.searchTerms);
$scope.currentPage = 0;
$scope.results.documents = [];
$scope.isSearching = true;
return searchService.search($scope.searchTerms, $scope.currentPage).then(function(es_return) {
var totalItems = es_return.hits.total;
var totalTime = es_return.took;
var numPages = Math.ceil(es_return.hits.total / $scope.itemsPerPage);
$scope.results.pagination = [];
for (var i = 1; i <= 100; i++) {
if(totalItems > 0)
$scope.results.totalItems = totalItems;
$scope.results.queryTime = totalTime;
$scope.results.pagination = searchService.formatResults(es_return.hits.hits);
$scope.results.documents = $scope.results.pagination.slice($scope.currentPage, $scope.itemsPerPage);
}
}
),
function(error){
console.log('ERROR: ', error.message);
$scope.isSearching = false;
}
};
I'm not quite sure what is wrong? I'm thinking it has something to do with $scope, but I'm not sure. The query works when I use it Sense plugin for ES and it also works if I just type in a search term instead of selecting it from the autocomplete dropdown.
If it is $scope, what am I missing?
UPDATE
All shards failed for phase: [query_fetch]
org.elasticsearch.search.SearchParseException: [hugetestindex][0]: from[-1],size[-1]: Parse Failure [Failed to parse source [{"query":{"multi_match":{"query":{"_index":"hugetestindex","_type":"doc","_id":"57","_score":3.877801,"_source":{"ymme":"bourne supremacy"}},"fields":["content","title"],"operator":"and"}},"size":100,"from":0,"highlight":{"fields":{"title":{"number_of_fragments":0},"content":{"number_of_fragments":10,"fragment_size":300}}}}]]
UPDATE 2 Object {_index: "hugetestindex", _type: "doc", _id: "56", _score: 2.5276248, _source: Object}
I think that is the problem, instead of a search terms, its receiving "Object"....?
UPDATE 3So basically it goes like this,
[Object, Object, Object, Object, Object]
0: Object
_id: "229"
_index: "hugetestindex"
_score: 3.3071127
_source: Object
ymme: "bourne supremacy"
__proto__: Object
_type: "doc"
__proto__:
Object1:
Object2:
Object3:
Object4:
Object
length: 5
__proto__: Array[0]
where "bourne supremacy" is the value of the ymme field in the _source Object, the array at the top with the 5 objects is the es return, es_return.hits.hits - this last hits, is the array.
The way you deconstruct your object is by doing something like the following:
object.data.hits.hits._source.field_name;
The above is only a notation to get the value of a single field, you might need to do a loop for each of those values so maybe something like:
$scope.list = []
for hit in object.data.hits.hits {
$scope.list.push(hit._source.field);
}
console.log(list);
Then from your HTML you want to use this list by doing an ng-repeat with it or something similar to get each of the terms in the list.
<div ng-repeat="term in list">{{term}}</div>
If you can update your question with how your object looks and what data you want from it, I can update this answer to match it exactly.
UPDATE
To match your data structure, I'm assuming you want to extract each of the ymme values from those objects. You need to do the following:
<div ng-repeat="object in es_return.hits.hits">
{{object._source.ymme}}
</div>
Just make sure "es_return" is a $scope variable so you can access it as above or just do:
$scope.es_return = es_return;
In your Angular code

AngularJS and JSON returns undefined

Hi I have got a data in LocalStorage as JSON string:
[
{"Date":"28/04/2016","Time":"08:00","Title":"Title 1"},
{"Date":"28/04/2016","Time":"08:30","Title":"Title 2"}
]
And my module.factory looks like:
module.factory('$schedule', function() {
var schedule = {};
var result = JSON.parse(localStorage.getItem('myAgenda'));
schedule.items = [{
title: result.Title,
date: result.Date,
time: result.Time
}];
return schedule;
});
When I am trying to get data it returns undefined. When I try to get a specific object like:
console.log(result[0].Title);
It works fine and shows only the first element. I guess I missing each definition but don't know how to do it. Please help me to get all results in my schedule.items.
And I am passing the result as items into:
module.controller('ScheduleController', function($scope, $schedule) {
$scope.items = $schedule.items;
});
Many thanks.
You are trying to access fields in an array without mentioning wich array element you want to access. If you want to enumerate all agenda entries and add them to your array, it should look something like this:
module.factory('$schedule', function () {
var schedule = [];
var result = JSON.parse(localStorage.getItem('myAgenda'));
result.forEach(function (date) {
schedule.push({
title: date.Title,
date: date.Date,
time: date.Time
})
})
return schedule;
});
You should use .map over array, also add missing } in your last element of array.
var schedule = [];
//assuming result returns an array.
schedule = result.map(function(value){
return {
title: value.Title,
date: value.Date,
time: value.Time
};
})
Not familiar with module.factory, but it looks like result is an array of objects and you're accessing it like a single object when creating schedule.items.
You might have to iterate over the array and create an item per object in result.

Resources