I am working on an ionic app that loads data from firebase. In this case I have a .factory called NoteStore that reads a specific table in firebase (eg "lakes").
{
"lake": {
"one": {
"bio": "xxxx",
"shortname": "xxxx",
"name": "xxxxx",
"reknown": "xxxx",
"image":"xxxxx"
},
"two": {
"bio": "xxxx",
"shortname": "xxxx",
"name": "xxxxx",
"reknown": "xxxx",
"image":"xxxxx"
}
}
}
This is the .factory code that reads from firebase:
//get all lake activites
getAllLakes: function(){
return $firebaseArray(ref.child('lake'));
},
//get individual lake activites
getLake: function(lakeId){
return $firebaseObject(ref.child('lake').child(lakeId));
}
My app Controller then gets the data through the NoteStore and calling a function "getAllLakes():
app.controller('LakeActivitiesListController', function($scope, NoteStore, $localStorage) {
$scope.alllakes = NoteStore.getAllLakes();
}
The main problem is that I want to access individual objects from the "lake" table in firebase so that I can be able to store them in localStorage.
This then displays array of objects as below:
When I just create an object as shown below and save to localStorage, it works fine, as shown in the image below.
var myObj = [
{
name: 'james',
title:'doctor'
},
{
name: 'jojo',
title:'doctor'
}
];
console.log(myObj);
//
window.localStorage['lakes'] = JSON.stringify(myObj);
$scope.data = JSON.parse(window.localStorage.getItem('lakes'));
I am working on my college project that is overdue. Please help. All I want is to be able to access an array that contains objects from firebase so that I can store them in localStorage.
Please.
angular.forEach is the way, here is an example:
Example with array of objects iteration:
var array_of_objects = [{name: 'Jimi', gender: 'male'},{name: 'Peter', gender: 'male'},{name: 'Bob', gender: 'male'}];
angular.forEach(array_of_objects, function(item, index) {
console.log(item, index);
});
Example with object iteration:
var my_object = {name: 'Jimi', gender: 'male', age: '25'};
angular.forEach(my_object, function(value, key) {
console.log(value, key);
});
In your case you want to make an angular.forEach on $scope.alllakes and then push the object that you want in the storage
The problem is, that you have an object not an array. You can loop through the different members of you object with
for(var propertyName in myObject) {
// propertyName is what you want
// you can get the value like this: myObject[propertyName]
}
Related
I have looked at simular threads, but to no success. What I'm trying to do is update my localstorage through an update function. The functions look as follows:
The code to make the variables to call:
var localProfile = JSON.parse(localStorage.getItem("profile"));
if(localProfile != undefined && localProfile.length>0)
{ this.profiles = localProfile; }
else {
this.profile = [
{ id: "1526", name: "berserk", password: "berserk", age: "31", gender: "male"},
{ id: "1358", name: "Johnathan", password: "test", age: "17", gender: "male"},
{ id: "2539", name: "Britney", password: "test", age: "18", gender: "female"},
{ id: "1486", name: "Kevin", password: "test", age: "7", gender: "male"},
{ id: "7777", name: "jesus", password: "holy", age: "unknown", gender: "male"},
{ id: "6666", name: "satan", password: "hell", age: "unknown", gender: "unknown"}
];
}
The code to update the variable:
this.updateProfile = function(profile) {
profile.updating = false;
console.log(profile);
localStorage.setItem("profile", profile);
}
As I noted in the title I am currently using Angular. I have used the console.log(-line and the response seems to be exactly what it's supposed to be. I have tried using JSON.parse( and JSON.stringify as well as a couple of other combinations. I seem to get either the error above or another error when trying to reload the page. Apperently I either cannot execute the statement, or I end up corrupting the data so reloading the page returns a simular error.
In case the data in variable profile is in doubt:
Array [ Object, Object, Object, Object, Object, Object ]
And when taking a closer look at the data:
age:"17"
gender:"male"
id:"1358"
name:"johnathan"
password:"test"
The other object looks identical with no weird defaults in them. I already took care of the $$hashkey just incase that was the problem.
Any help on how to execute the call correctly is greatly apreciated and if the information is insufficient please do tell.
The problem is your not using JSON.stringify when saving your data. So when you are parsing from localStorage its not json.
Add a factory to be used across your application that handles JSON.parse() and JSON.stringify()
.factory('LocalStorageUtil', function() {
return {
get: get,
set: set,
remove: remove
}
function get(key) {
return JSON.parse(localStorage.getItem(key));
}
function set(key, val) {
localStorage.setItem(key, JSON.stringify(val));
}
function remove(key) {
return localStorage.removeItem(key);
}
})
Here is a JS Bin tiny sample app using this LocalStorageUtil.
http://jsbin.com/fijagiy/2/edit?js,output
In my app I have Students who can Enroll in Classes.
An Enrollment records the start and end dates along with a reference to which Class.
The Class has details like a class name and description.
Student (1) - (N) Enrollment (1) - (1) Class
Therefore
Student (1) - (N) Class
This is what I would like the object to look like.
{
"studentId": 1,
"name": "Henrietta",
"enrolledClasses": [
{
"enrollmentId": 12,
"startDate": "2015-08-06T17:43:14.000Z",
"endDate": null,
"class":
{
"classId": 15,
"name": "Algebra",
"description": "..."
}
},
"enrollmentId": 13,
"startDate": "2015-08-06T17:44:14.000Z",
"endDate": null,
"class":
{
"classId": 29,
"name": "Physics",
"description": "..."
}
}
}
But my RESTful API cannot (easily) output the full nested structure of the relationship because it's ORM can't do Many to Many with Through relationships. So I get the student and their multiple enrollments, but only a reference to the class for each, not the details. And I need to show the details, not just an Id.
I could wait for the student object to be available and then use the references to make additional calls to the API for each classId to get details, but am not sure how, or even if, to then integrate it with the student object.
This is what I have so far.
function findOne() {
vm.student = StudentsResource.get({
studentId: $stateParams.studentId
});
};
This is what I get back from my API
{
"studentId": 1,
"name": "Henrietta",
"enrolledClasses": [
{
"enrollmentId": 12,
"startDate": "2015-08-06T17:43:14.000Z",
"endDate": null,
"class": 15
},
"enrollmentId": 13,
"startDate": "2015-08-06T17:44:14.000Z",
"endDate": null,
"class": 29
}
}
And for the class details I can them one at a time but haven't figured out how to wait until the student object is available to push them into it. Nor how to properly push them...
{
"classId": 15,
"name": "Algebra",
"description": "..."
}
{
"classId": 29,
"name": "Physics",
"description": "..."
}
Question
Is it good practice to combine the student and class(es) details through the enrollments, as one object?
If so, whats the most clear way to go about it?
If not, what is another effective approach?
Keep in mind that the app will allow changes to the student details and enrollments, but should not allow changes to the details of the class name or description. So if Angular were to send a PUT for the object, it should not try to send the details of any class, only the reference. This would be enforced server side to protect the data, but to avoid errors, the client shouldn't try.
For background, I'm using SailsJS and PostgreSQL for the backend API.
So basically on the Sailsjs side you should override your findOne function in your StudentController.js. This is assuming you are using blueprints.
// StudentController.js
module.exports = {
findOne: function(req, res) {
Student.findOne(req.param('id')).populate('enrollments').then(function(student){
var studentClasses = Class.find({
id: _.pluck(student.enrollments, 'class')
}).then(function (classes) {
return classes
})
return [student, classes]
}).spread(function(student, classes){
var classes = _.indexBy(classes, 'id')
student.enrollments = _.map(student.enrollments, function(enrollment){
enrollment.class = classes[enrollment.class]
return enrollment
})
res.json(200, student)
}).catch(function(err){
if (err) return res.serverError(err)
})
}
}
// Student.js
module.exports = {
attributes: {
enrollments: {
collection: 'enrollment',
via: 'student'
}
// Rest of the attributes..
}
}
// Enrollment.js
module.exports = {
attributes: {
student: {
model: 'student'
}
class: {
model: 'class'
}
// Rest of the attributes...
}
}
// Class.js
module.exports: {
attributes: {
enrollments: {
collection: 'enrollment',
via: 'class'
}
// Rest of the attrubutes
}
}
Explanation:
1. the _.pluck function using Lo-dash retuns an array of classIds and we find all of the classes that we wanted populated. Then we use the promise chain .spread(), create an array indexed by classid and map the classIds to the actual class instances we wanted populated into the enrollments on the student returned from Student.findOne().
2. Return the student with enrollments deep populated with the proper class.
source: Sails.js populate nested associations
Let's say I have this Json ..
{
"name": "Mark",
"gender": "male",
"account1": {
"accountNo": 1201,
"balance": 300
},
"account2": {
"accountNo": 1354,
"balance": 5000
}
}
What I expect is like ..
$scope.myArray = [
{
"accountNo": 1201,
"balance": 300
},
{
"accountNo": 1354,
"balance": 5000
}
];
In AngularJS, how can I pick some part of Json data and push it into an array iteratively( I mean, when I have account1, account2 account3 or more, it can still add them into the array).
You could normally just assign the array over, but in this scenario that is not an option because your array is psuedo.
Ideally you would like to be able to do what this answer (related question) does: How to return and array inside a JSON object in Angular.js which is simply
$scope.myArray = json.accounts;
However, as noted, you do not have an accounts array so you need to make one.
var accounts = [];
for(var key in json){
if( !json.hasOwnProperty(key) // skip prototype extensions
|| !json[key].hasOwnProperty("accountNo") //skip non account objects
) continue;
accounts.push(json[key]);
}
And now you may use this array
$scope.myArray = accounts;
You can access Json data like an array. Like var foo = { ... , 'bar' = 'value', ... } you could get foo value by doing this for['bar']. So, by knowing this, you simply do something like
var arr = [];
for (var i = 0; i < 10; i++) {
arr.push(foo['account'+i]);
}
Although, this has nothing to do with angularjs.
how to search array of object in backbone js.The collection contain persons model.
[{
name: "John",
age: "18",
likes: {
food: "pizza",
drinks: "something",
}
},
......
]
how can i get persons who likes something.
i did try collection.where({likes :{food : "pizza"}});
Since your food property is in an object on the Person's attributes, using where (which by default just looks at the flat attributes) isn't going to work. You can use the filter method to apply a truth test to all of the items in your collection and just get the ones that pass.
In the code you posted, it doesn't look like you have a Backbone Collection proper, just a regular array of objects.
Since Underscore is on the page, you can use it to help filter through your list.
var people = [
{
name: "John",
age: "18",
likes: {
food: "pizza",
drinks: "something",
}
},
......
];
var likesPizza = _.filter(people, function(person) {
return person.likes.food === "pizza";
});
If it is in fact a Backbone Collection, you can use
this.collection.filter(people, function(person) {
return person.get('likes').food === "pizza";
});
I'm sure I make one of these Backbone newbie mistakes but after a hour of searching around I didn't found a solution.
Here's the problem: When I try to get a filtered model from my collection theres a type error "productCollection.getProductByName("M020012").toJSON is not a function".
But if I change the filter method to a simple "return this.at(0)" I get a valid model.
Why is that and what is the solution?
Here's the JSFiddle
var products = [{
"name": "M020013",
"gender": "M",
"pictures": [{
"picture": {}}]},
{
"name": "M020012",
"gender": "M",
"pictures": [{
"picture": {}}]},
{
"name": "M020011",
"gender": "M",
"pictures": [{
"picture": {}}]}
];
var Product = Backbone.Model.extend({});
var ProductCollection = Backbone.Collection.extend({
model: Product,
getProductByName: function(productName) {
//return this.at(0);
return this.filter(
function(product) {
return product.get('name') === productName;
});
}
});
var productCollection = new ProductCollection();
productCollection.on('reset', function() {
console.log('reset');
console.log(productCollection.getProductByName('M020012'));
console.log(productCollection.getProductByName('M020012').toJSON());
});
productCollection.reset(products);
It's because filter returns an array of models. And an Array in javascript does not have a toJSON function.
Since you want to return a model instead of an array, then you can use the find in place of filter. The find method returns the first model that matches the criteria
Here's what the code would look like:
getProductByName: function(productName) {
return this.find(function(production) {
return production.get('name') === productName;
});
}