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.
Related
I'm having a strange problem with my code. There is an object that comes from an API call where videos are stored and I need to add the number of videos on the website. But sometimes there can be "null" coming from API call and obviously, I don't have to show the length of the null value.
As I wrote this code which works when I try on editors, but when I use it on my project it gives an error Cannot convert undefined or null to object. Can anyone give me an idea or hint of what I'm doing wrong? And sorry if I explained unclearly, this is my very first post here. Thank you!
const object = {
background_video: null,
vimeo_branded: 'video url',
vimeo_unbranded: "video url"
}
const removeFalsyElement = object => {
let sum = 0;
Object.keys(object).forEach(key => {
if (object[key]) {
sum += 1;
}
});
return sum;
};
console.log(removeFalsyElement(object)) // output should be 2.
The Object.keys method expects an object always. if we pass null we would get the above mentioned error
const removeFalsyElement = (object = {}) => {//default value for object in case it is null. Object.keys needs an object always
let sum = 0;
Object.keys(object).forEach(key => {
if (object[key]) {
sum += 1;
}
});
return sum;
};
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 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;
I'm trying to fetch an object 'single Post' within an object 'Posts' from a json file within meteor, which looks like this.
I found an effective way of doing it, using underscore findWhere to get to it. this is the code
_.findWhere(_.findWhere(CategoryCollection.find().fetch(),
{"_id":"CategoryPublication-5"}).posts,{"ID":46});
however when i put this into meteor, i'm getting undefined
this is the code i used
Template.CategoryArticleSingle.helpers({
articles: function () {
var id = FlowRouter.getParam('ID')
var category = FlowRouter.getParam('category')
console.log(CategoryCollection.find().fetch());
let match = _.findWhere(_.findWhere(CategoryCollection.find().fetch(), {"_id":category}).posts,{"ID": id});
console.log("match",id,category,match);
return match;
}
});
Why am i getting undefined
update.
would this be correct? i substituted the 47 id, with just id so i can use it for any link.
Im getting "category" is read-only error.
Template.CategoryArticleSingle.helpers({
articles: function () {
var id = FlowRouter.getParam('ID')
var category = FlowRouter.getParam('category')
console.log(CategoryCollection.find().fetch());
const category = CategoryCollection.find().fetch().find(c => c._id === id);
let post = null;
if (category) {
post = category.posts.find(p => p.ID === id);
}
console.log("post",id,category,post);
return post;
}
});
There's no need to use lodash/underscore's findWhere. This functionality is built into ES2015. Also, you may consider breaking up the code into a few lines to make it more legible.
const category = CategoryCollection.find().fetch().find(c => c._id === 'CategoryPublication-5');
let post = null;
if (category) {
post = category.posts.find(p => p.ID === 47);
}
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);
});
};