Find the identifier of a certain data set in firebase - angularjs

I'm searching through clients invoices
These invoices are stored within the client json.
so...
clients: {
... : {
invoices: {
},
},
}
I'm doing this by this:
var ref = new Firebase(fbUrl+'/clients/'+client+'/invoices/');
ref.on("value", function(snapshot) {
var list = snapshot.val();
angular.forEach(list, function(item) {
if(item.settings.number == id)
{
console.log(item.id());
invoice.details = item;
}
})
});
Inside the "if" how do I get the unique id auto generated by Firebase? In your html your able to do $id typically.

Once you call snapshot.val(), you're just dealing with a Javascript object. See the documentation for angular.forEach. You just need to specify a second argument to the function.
angular.forEach(list, function(item, key) {
...
});

Related

Vue Old Array Mirroring New Array

I have two arrays declared in my data
data() {
return {
infeed_data:[],
infeed_model:[],
}
},
Once the page is mounted, the following method is kicked off
mounted() {
this.get_rolls_infeed()
},
This method makes a call to my api, then assigns the response to both infeed_data and infeed_model. I then do a for loop and create new key/values on the infeed_model, however the new key/values show up in the infeed_data.
get_rolls_infeed(){
var vthis = this;
axios.post(myapiurl)
.then(function(response){
vthis.infeed_data = response.data[0]
vthis.infeed_model = response.data[0]
vthis.infeed_model.forEach(function(record, index){
vthis.infeed_model[index].usage_type = 0
})
})
},
My Vue html
<b>Infeed Data</b>
<p>{{infeed_data}}</p>
<br />
<b>Infeed Model</p>
<p>{{infeed_model}}</p>
Rendered html to show how _data is mirroring _model
Can you try to do this instead of your code?
vthis.infeed_data = response.data[0];
vthis.infeed_model = response.data[0].slice();

An empty array is returned when calling $http.get it within a service [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I want to get the name from an array that is being generated from $http.get, however this is returning an empty array. When i do a console it see the array populated however when i loop inside the array to get the value of name property based on whether an id is equal to a certain, the array is empty.
In my controller i have a service call that shall return the name value.
var params = { Id: $scope.Id, SettingId: $scope.SettingId };
$scope.selectedUserName = helloService.getSelectedUserName($scope.UserId, params);
In my service
I have used the getUserList function to populate the list of user in a dropdown and it works by generating the array with the values.
However When i got another page , i want to be able to display the name of the selected user, so I wanted to use the same getUserList function to retrieve the name
this.getUserList = function (val) {
var usersObj = [];
var url = "/api/v1/hello/getusers";
var params = { Id: val.Id, SettingId: val.SettingId };
var config = { params: params };
var promise = $http.get(url, config)
.then(function (response) {
angular.forEach(response.data, function (key, value) {
angular.forEach(key, function (k, index) {
usersObj[index] = ({ userId: k.userId, name: k.name});
});
});
},
function errorCallback(response) {
console.log("Unable to perform get request");
throw response;
});
var usersList = usersObj;
return usersObj;
};
this.getSelectedUserName = function (id, param) {
var name = "";
var userList =this.getUserList(param);
angular.forEach(userList, function (value, key) {
if (value.userId == id)
name = value.name;
});
return name;
}
Array length is 0 but if i do a console.log(userList) before the loop , the array display the list of user data
this.getSelectedUserName = function (id, param) {
var name = "";
var userList =this.getUserList(param);
console.log(userList) ;
angular.forEach(userList, function (value, key) {
if (value.userId == id)
name = value.name;
});
return name;
}
Thank you for kind responses.
Please see screenshot
This is simple Javascript, not specific to Angular. You can do
userList.forEach(user => {
if(user.userId === id) {
name = user.name;
}
});
return name;
you can try like this.
here we are using a async await.
Service
this.getUserList = function (val) {
var usersObj = [];
var url = "/api/v1/hello/getusers";
var params = { Id: val.Id, SettingId: val.SettingId };
var config = { params: params };
return new Promise((resolve, reject) => {
$http.get(url, config)
.then(function (response) {
angular.forEach(response.data, function (key, value) {
angular.forEach(key, function (k, index) {
usersObj[index] = ({ userId: k.userId, name: k.name});
});
});
},
function errorCallback(response) {
console.log("Unable to perform get request");
throw response;
});
var usersList = usersObj;
resolve(usersObj);
});
};
this.getSelectedUserName = async function (id, param) {
var name = "";
var userList = await this.getUserList(param);
console.log(userList);
angular.forEach(userList, function (value, key) {
if (value.userId == id)
name = value.name;
});
return name;
}
let me know if it is working or not.
EDIT:
If you're only trying to match one id in the array of users you don't even need to loop:
anArray = source.filter(source => source.toLowerCase().indexOf(id) === 0);
or
anObject = source.find(obj => obj.id === id);
Which Angular version is this? Your tag denotes 2.+ but you have $scope there which is ng1.x
Why can't you use ngFor in your view since you already have your arrays. You don't need to sort them in the control.
component
this.getSelectedUserName = function (id, param) {
let name = ""; // should be array if you want to add unames to it
let userList = this.getUserList(param);
// what is `angular` here? And why loop here? Use ngFor in view.
angular.forEach(userList, function (value, key) {
if (value.userId == id){
name = value.name; // will be overwritten each time
// should be name.push(value.name); // but loop in view instead
}
});
// this.users = name; // for your original sorted version
this.users = userList;
}
In your view
<li *ngFor="let user of users; index as i;>
{{user.name}}
</li>

Extending $firebaseArray with an extended $firebaseObject

Trying to cut down code repetition, I've set up a $firebaseArray extension as follows:
var listUsersFactory = $firebaseArray.$extend({
$$added: function (snap) {
return new Customer(snap);
},
$$updated: function (snap) {
var c = this.$getRecord(snap.key);
var updated = c.updated(snap);
return updated;
},
});
and the Customer code:
function Customer(snap) {
this.$id = snap.key;
this.updated(snap);
}
Customer.prototype = {
updated: function(snap) {
var oldData = angular.extend({}, this.data);
this.data = snap.val();
// checks and such
}
}
This works wonders when loading, showing and saving a list of customers, and I'm satisfied with it.
Now, the problem lies in retrieving a single customer and its detail page, because the Customer object isn't an extension of $fireObject and is therefore lacking a $save method
Single customer loading:
customersRef.once("value", function(snapshot) {
if(snapshot.child(uuid).exists())
{
customersFactory.customerDetails = new Customer(snapshot.child(uuid));
return deferred.resolve();
}
}
but when I call customersFactory.customerDetails.$save() I get an error
How can I extend my class so that it works for both array and single object uses?
I couldn't find a way to do this, so I ended up using the $firebaseArray and getting single records off that to pass as details, in case anyone's wondering

Can't get Firebase reference to ID to define current user

I think I am getting my keys, arrays, values and IDs mixed up here but can't seem to figure it out.
I want a way to get the current user in a ProfileCtrl controller. This is my current implementation using promises, $waitForAuth and once. But I am not sure if implementing currently.
var user = "";
var key = "";
var uids = Users.allUIDs();
console.log(uids);
Auth.$waitForAuth().then(function () {
var uid = Auth.$getAuth().uid;
console.log(uid);
for (var i = 0; i < uids.length; i++) {
console.log(uids[i].value().toString());
if (uids[i].value() == uid) {
var userKeyRef = new Firebase(firebaseUrl + uids + uids[i]);
userKeyRef.once('value').then(function(snapshot) {
key = snapshot.val();
}).then(function(){
user = new Firebase(firebaseUrl + users).child(key).val();
});
console.log(user);
console.log('User exists')
break;
}
}
$scope.user =user;
}).catch(function (error) {
console.log(error);
})
I do a check of the uids in an array, and if they match the authenticated user, I get the key from within the uids array and use that key to find the user object in the users array. Here is my database:
{
"uids" : {
"7d34fb85-813c-4586-857e-f062aed67f32" : {
"-KDQDk5vwJXmFngwI7iQ" : {
"registered" : true
}
}
},
"users" : {
"-KDQDk5vwJXmFngwI7iQ" : {
"email" : "random#gmail.com",
"firstname" : "Random",
"lastname" : "Person",
"uid" : "7d34fb85-813c-4586-857e-f062aed67f32"
}
}
}
For a clearer example, when I console.log the uids as it is returned from my service, it looks like:
Which means the uids are coming through?
Here is my code to get the uids:
app.factory('Users', ['$firebaseArray','$firebaseObject', 'Auth', function ($firebaseArray, $firebaseObject, Auth) {
var ref = new Firebase("https://urlformyapp.firebaseio.com");
var users = $firebaseArray(ref.child('users'));
var uids = $firebaseArray(ref.child('uids'));
return {
all: function () {
return users;
},
allUIDs: function () {
return uids;
},
get: function (id) {
// Simple index lookup
return users[id];
}
}
}])
Could someone tell me what is going wrong? Why does uids[i].value.toString() not print anything? Is there anything wrong with my code logic given the structure of my DB?

passing data to a collection in backbone

So I am trying storing product types from a json file before trying to add them to a collection but am getting some strange results (as in I dont fully understand)
on my router page i setup a variable for cached products as well as product types
cachedProductTypes: null,
productType : {},
products : {},
getProductTypes:
function(callback)
{
if (this.cachedProductTypes !== null) {
return callback(cachedProductTypes);
}
var self = this;
$.getJSON('data/product.json',
function(data)
{
self.cachedProductTypes = data;
callback(data);
}
);
},
parseResponse : function(data) {
result = { prodTypes: [], products: [] };
var type;
var types = data.data.productTypeList;
var product;
var i = types.length;
while (type = types[--i]) {
result.prodTypes.push({
id: type.id,
name: type.name,
longName: type.longName
// etc.
});
while (product = type.productList.pop()) {
product.productTypeId = type.id,
result.products.push(product);
}
};
this.productType = result.prodTypes;
console.log( "dan");
this.products = result.products;
},
showProductTypes:function(){
var self = this;
this.getProductTypes(
function(data)
{
self.parseResponse(data);
var productTypesArray = self.productType;
var productList=new ProductsType(productTypesArray);
var productListView=new ProductListView({collection:productList});
productListView.bind('renderCompleted:ProductsType',self.changePage,self);
productListView.update();
}
);
}
when a user goes to the show product types page it runs the showProductsType function
So I am passing the products type array to my collection
on the collection page
var ProductsType=Backbone.Collection.extend({
model:ProductType,
fetch:function(){
var self=this;
var tmpItem;
//fetch the data using ajax
$.each(this.productTypesArray, function(i,prodType){
tmpItem=new ProductType({id:prodType.id, name:prodType.name, longName:prodType.longName});
console.log(prodType.name);
self.add(tmpItem);
});
self.trigger("fetchCompleted:ProductsType");
}
});
return ProductsType;
now this doesnt work as it this.productTypesArray is undefined if i console.log it.
(how am I supposed to get this?)
I would have thought I need to go through and add each new ProductType.
the strange bit - if I just have the code
var ProductsType=Backbone.Collection.extend({
model:ProductType,
fetch:function(){
var self=this;
var tmpItem;
//fetch the data using ajax
self.trigger("fetchCompleted:ProductsType");
}
});
return ProductsType;
it actually adds the products to the collection? I guess this means I can just pass an array to the collection and do not have to add each productType?
I guess this means I can just pass an array to the collection and do not have to add each productType?
Yes, you can pass an array to the collection's constructor, and it will create the models for you.
As far as your caching code, it looks like the problem is here:
if (this.cachedProductTypes !== null) {
return callback(cachedProductTypes);
}
The callback statement's argument is missing this - should be return callback(this.cachedProductTypes).

Resources