i want to get specific value from a response, here is my js
$scope.cari = function () {
$http.get('http://localhost:8089/MonitoringAPI/webresources/login?a='+$scope.userid+'&d='+$scope.password).then(function(response){
$scope.reslogin = response.data;
$scope.reslogin2 = response.data.lsmenu.idmenu;
console.log($scope.reslogin);
console.log($scope.reslogin2);
});
};
but when i console.log the $scope.reslogin2gives me undefined value. here is my response
[{"userid":"1234",
"username":"ristian",
"posisi":"ITSupport",
"lsmenu":[{"idmenu":"1","parentidmenu":"11","parentnamemenu":"Monitoring","urlmenu":"lalala.html"}]}]
According to what you posted, your response is an array (so is the lsmenu). Therefore you should get the first element of the array and also the first element from the lsmenu.
$scope.cari = function () {
$http.get('http://localhost:8089/MonitoringAPI/webresources/login?a='+$scope.userid+'&d='+$scope.password).then(function(response){
$scope.reslogin = response.data;
$scope.reslogin2 = response.data[0].lsmenu[0].idmenu;
console.log($scope.reslogin);
console.log($scope.reslogin2);
});
};
It should be, response.data is an array and lsmenu is also an array
$scope.reslogin2 = response.data[0].lsmenu[0].idmenu;
Related
Why do I receive an error message in the console that getStoredQuests.push is not a function at Object.addQuestionOnLocalStorage
class Question{
constructor(id, questionText, options, correctAnswer) {
this.id = id;
this.questionText = questionText;
this.options = options;
this.correctAnswer = correctAnswer;
}
}
let questionLocalStorage = {
setQuestionCollection: (newQuestion) => {
localStorage.setItem('questionCollection', JSON.stringify(newQuestion));
},
getQuestionCollection: () => {
return JSON.parse(localStorage.getItem('questionCollection'));
},
removeQuestionCollection: () => {
localStorage.removeItem('questionCollection');
}
}
newQuestion = new Question(questionId, newQuestText.value, optionsArr, corrAnswer);
getStoredQuests = questionLocalStorage.getQuestionCollection();
getStoredQuests.push(newQuestion);
questionLocalStorage.setQuestionCollection(getStoredQuests);
The error is because getStoredQuests is not an array. You have probably not considered if there is no question in local storage initially, then localStorage.getItem('questionCollection') will return empty string or it might be case that you have some value with key questionCollection in local storage but is not in proper format to to be parsed as JSON array object.
For the first case solution is to check if localStorage.getItem('questionCollection') is empty then return empty array from getQuestionCollection and for the second case you to need to properly format the array '(serialize the array to be stored with JSON.stringify)'.
To let your problem understand properly, open up console see if there are red lines
I am using laravel and vuejs to create a chat app. I have encrypted my response in laravel by doing like this as I do not want anyone to see my response in console also:-
public function get()
{
$contacts = User::where('id', '!=', auth()->id())->get();
$unreadIds = Message::select(\DB::raw('`from` as sender_id,count(`from`) as messages_count'))
->where('to', auth()->id())
->where('read', false)
->groupBy('from')
->get();
$contacts = $contacts->map(function($contact) use ($unreadIds) {
$contactUnread = $unreadIds->where('sender_id', $contact->id)->first();
$contact->unread = $contactUnread ? $contactUnread->messages_count : 0;
return $contact;
});
$contacts = base64_encode($contacts);
return response()->json($contacts);
}
Now when I wish to access this value to display data in vue js, I am doing something like this:-
axios.get(this.globalUrl+'/contacts')
.then((response) => {
let encryptData = atob(response.data);
console.log(encryptData);
//data received after de-converting
/*[{"id":2,"phone":null,"name":"Casimir Morar MD","email":"clint.haag#hartmann.info","profile_image":null,"created_at":null,"updated_at":null,"unread":0},{"id":3,"phone":null,"name":"Lina Prosacco","email":"okeefe.camila#gmail.com","profile_image":null,"created_at":null,"updated_at":null,"unread":0},{"id":4,"phone":null,"name":"Miss Aglae Emard DDS","email":"qcarter#yahoo.com","profile_image":null,"created_at":null,"updated_at":null,"unread":0},{"id":5,"phone":null,"name":"Demarco Kilback","email":"kessler.coy#swift.com","profile_image":null,"created_at":null,"updated_at":null,"unread":0},{"id":6,"phone":null,"name":"Tyrell Ziemann Sr.","email":"clementina.kautzer#price.org","profile_image":null,"created_at":null,"updated_at":null,"unread":0},{"id":7,"phone":null,"name":"Ella Hand","email":"areichel#watsica.com","profile_image":null,"created_at":null,"updated_at":null,"unread":0},{"id":8,"phone":null,"name":"Dr. Maxie O'Hara DDS","email":"wallace31#yahoo.com","profile_image":null,"created_at":null,"updated_at":null,"unread":0},{"id":9,"phone":null,"name":"Mrs. Mattie Monahan IV","email":"ernser.pasquale#hotmail.com","profile_image":null,"created_at":null,"updated_at":null,"unread":0},{"id":10,"phone":null,"name":"Bradly Crona","email":"lehner.cordie#pagac.com","profile_image":null,"created_at":null,"updated_at":null,"unread":0},{"id":11,"phone":null,"name":"Orland Kihn","email":"jacobs.wyman#yahoo.com","profile_image":null,"created_at":null,"updated_at":null,"unread":0}]*/
let finalArray = encryptData.map(function (obj) {
return obj;
//this.contacts.push(obj);
});
console.log(finalArray);
this.contacts = finalArray;
});
Here I am getting the data in the encryptData variable as an array of objects but proceeding further, every time I am getting this error:-
Uncaught (in promise) TypeError: encryptData.map is not a function
Please help me in finding the solution thanks.
You're probably missing a JSON.parse call:
axios.get(this.globalUrl + '/contacts')
.then((response) => {
let encryptData = JSON.parse(atob(response.data));
let finalArray = encryptData.map(function(obj) {
// ...
});
this.contacts = finalArray;
});
Basically:
your PHP script returns the base64-encoded data, in JSON format,
axios.get's callback receives this as a base64-encoded string,
atob base64-decodes the string (it's still a string at this point),
JSON.parse transforms it back into the actual data.
I have a dropdown and when one of the items is clicked, I call this function:
onClick(type) {
type.preventDefault();
let query = type.target.text;
PokeApi.pokemonType(query).then(function(data) {
console.log(data);
}.bind(this));
}
The console.log returns undefined.
When I do this:
onClick(type) {
type.preventDefault();
let query = type.target.text;
console.log(query);
console.log(typeof query);
PokeApi.pokemonType(query).then(function(data) {
console.log(data);
}.bind(this));
}
The first console.log will return the text of the dropdown item. The second console.log will return string. Now, when I pass query to PokeApi.pokemonType, I can get back a 404 error from the api and the third console.log returns undefined.
But if I pass in the text of the dropdown directly like this:
onClick(type) {
type.preventDefault();
PokeApi.pokemonType("ice").then(function(data) {
console.log(data);
}.bind(this));
}
Everything works perfectly fine and I get the correct object back from the api.
Any idea why this happening? What am I doing wrong?
You have to get the value of the dropdown selected element
var sel = document.getElementById('myDropdown'),
var selectedText = sel.options[sel.selectedIndex].value;
I have application on AngularJs.
I have variable in scope, which is initialized with data from API. $scope.receivedRequests = CurrentUserData.incomeRequests();
Cause request to API takes some time, $scope.receivedRequests is empty at start.
$scope.receivedRequests I've used with ng-repeat
<div class="full-row" ng-repeat="row in receivedRequests | filterByStatus:[State.PENDING] | partition:3 track by $index">
This data is also filtered.
But when I tried to replace this filtering into controller, like
$scope.filterByStatus = function (statuses) {
return $filter('filterByStatus')($scope.receivedRequests, statuses);
};
$scope.pendingRequests = $scope.filterByStatus([State.PENDING]);
$scope.pendingRequests were always empty.
How can I filter data in the controller?
.filter('filterByStatus', function () {
return function(arr, statuses) {
if (!arr) { return; }
return arr.filter(function(value) {
return statuses.some(function(val) {
return value.status == val;
});
});
};
});
$scope.receivedRequests is just array of elements, that have string property status (alos id, date etc.) as example : status : "Pending"
In that case I would use promises and split the code like this.
Factory service
app.factory('myService', function($http){
return {
getRequests: function(){
return $http.get('http://someurl');
}
}
})
Controller
app.controller('myController', function(myService){
$scope.filteredArray = [];
myService.getRequests()
.then( function(data){
$scope.filteredArray = $scope.filterFunction(data);
})
$scope.filterFunction = function(array){
//function logic
//...
}
})
Notes:
The trick here is done by calling the filtering function inside the then() function. This way you are sure the data from the API is been already fetched and after that you can filter it.
I am not sure how your $scope.recievedRequests object look, can you try the below... why don't you send the State.pending value with an associated key for your array.
$scope.filterByStatus = function (statuses) {
return $filter('filterByStatus')($scope.receivedRequests, statuses);
};
$scope.pendingRequests = $scope.filterByStatus({key: State.PENDING})[0];
I have an object (array type) ,its console representation looks like following image . please see the image
This array is created by restangulr using following code ,
restangularProvider.addResponseInterceptor(function (data, operation, what, url, response, deferred) {
if (operation == "getList") {
var extractedData;
extractedData = data.result;
extractedData.paginginfo = data.paginginfo;
return extractedData;
}
if (operation != "get") {
var item = { status: response.status };
feedBackFactory.showFeedBack(item);
}
return response.data;
});
How can I read the elements from this array, I want to extract properties like paginginfo ,also object collection
// The EDIT :1 js libraries I used here angularjsu 1.3.4, and restangular 1.4
My app.js : here I configured rest angular provider
restangularProvider.addResponseInterceptor(function(data, operation, what, url, response, deferred) {
if (operation == "getList") {
var extractedData;
extractedData = data.result;
extractedData.paginginfo = data.paginginfo;
return extractedData;
}
if (operation != "get") {
var item = {
status: response.status
};
feedBackFactory.showFeedBack(item);
}
return response.data;
});
// according to my knowledge this function will intercept every ajax call (api calls) and modify the response , unfortunately I need to apply custom modification because the getlist method must return collection but my api returning object, so according to restangular ,the above code is the possible solution, and here its fine its fetching the data.
userservice.js : this is angular service which using restangular
function(restangular) {
var resourceBase = restangular.all("account");
this.getUsers = function(pagenumber, recordsize) {
var resultArray = resourceBase.getList({
page: pagenumber,
size: recordsize
}).$object;
};
};
according to my knowledge .$object in restangulr resolve the promise and bring back the data, also I am getting the resultArray its looks like in the image in the console, here I can log this array so I think I got all the data from server and filled in this object. I applied some array accessing techniques available jquery and JavaScript like index base accessing , associate accessing but I am getting undefined ie.
resultArray[1] //undifiend;
In angular you can use angular.forEach(items, function(item){ //your code here});
Where items is the array you want to traverse.
If you want to access to one specific position use [], for example var item= items[5].
Then you can do item.property.
UPDATE
Your problem is that you are setting properties in an Array JS Object:
extractedData.paginginfo = data.paginginfo;
You should return the object data like it is and in your controller do something like:
var results= data.result;
var pagInfo= data.paginationInfo;
angular.forEach(results,function(result){});
It looks like the array is numerically indexed (0..1..5); you should be able to simply iterate through it using ForEach (in Angular) or .each (in Jquery).
Something like (JQuery):
$.each(array, function(key, value)
{
// key would be the numerical index; value is the key:value pair of the array index's element.
console.log(value.firstname); // should print the firstname of the first element.
});
First of all, as I said in the comments, you shouldn't be attaching named properties to arrays. Return an object thact contains what you need:
if (operation == "getList") {
return { values: data.result, paging: data.pagingInfo };
}
The getList() method returns a promise, so you need to use that:
this.getUsers = function(pagenumber, recordsize) {
resourceBase.getList({
page: pagenumber,
size: recordsize
}).then(function (data) {
console.log(data.values[0]);
console.log(data.paging.totalRecords);
});
};