Firebase search with param? - angularjs

so i just started with Firebase and AngularFire.
I've got this data structure:
friends
-JzKr-mrv-O7rlxrMi3_
creator: "111181498675628551375"
description: "dsa"
name: "das"
--JzKrahnTf47MXp8nAZx
creator: "111181498675628551320"
description: "ddasdassa"
name: "dasdadsadas"
Now i want to query with param creator = "111181498675628551320".
How can i do this ? I've tried this way:
.service('Friends', function ($firebase, store, $state) {
var friendsRef = new Firebase("url/friends");
friendsRef.authWithCustomToken(store.get('firebaseToken'), function (error, auth) {
if (error) {
// There was an error logging in, redirect the user to login page
$state.go('login');
}
});
var friendsSync = $firebase(friendsRef);
var friends = friendsSync.$asArray();
this.all = function () {
return friends;
};
this.getCreator = function(creator){
return friends.$getRecord(creator);
};
});
Anyone got maybe some dev reference how i should work with it?
Maybe i should make other call then url/friends?

AngularFire is a wrapper around the Firebase JavaScript SDK, which simplifies binding Firebase data to AngularJS views. When something is not obvious from the AngularFire documentation, refer to the Firebase JavaScript documentation.
You can read all about Firebase queries in the documentation. In that case what you'll need to do, is build the necessary query using Firebase's regular JavaScript SDK:
var ref = new Firebase('https://yours.firebaseio.com/friends');
var query = ref.orderByChild('creator').equalTo('111181498675628551320');
Then you can bind the resulting items to your view by using an AngularFire $firebaseArray():
$scope.friends = $firebaseArray(query);

Related

globally access data across all pages in REACT js

In header react component class have defined function Search
Search: function()
{
var author=$('#author').val();
var bookname=$('#title').val();
var isbn=$('#isbn').val();
var keywords=$('#keywords').val();
var publisher=$('#publisher').val();
var url=VDOMAIN+"/aodrbooks.php?action=srch&author="+author+"&isbn="+isbn+"&publisher="+publisher+"&name="+bookname+"&price=''";
$.ajax({url:url,
success: function(result){
resp = JSON.parse(result); //this data is an array
if(resp['count']==1){
location.href=VDOMAIN+"odrbooks?pagename=bkd&bid="+resp['results'][0]['bookid']+"&bkname="+resp['results'][0]['name'];
}
else{
location.href=VDOMAIN+"odrbooks?pagename=cat&type=&author="+author+"&bkname="+bookname;
}
}
});
},
here how do i make my resp data globally such thAT I can access it in any page in any component?
I tried using this.state.data=resp ,this.props.data=resp and this.setState({data:resp})
Use state container for that purpose. The most popular one right now is https://github.com/reactjs/react-redux
You can dispatch an action and store successful response in Your reducer which represents Your application state.
Then connect that reducer to the component that needs resp data and use it through props.

How can I save data in forEach loop?

I create a forEach loop. I can access data from Firebase with this loop and I can change variable. But I can not save these changes on Firebase. How can I save these changes? Here's my code:
var posts = $firebaseArray(ref);
posts.$loaded().then(function(item){
item.forEach(function(childSnapshot){
var num = childSnapshot.point-1;
childSnapshot.lastPoint = num;
});
});
You're using the AngularFire framework, which builds UI bindings on top of Firebase's regular JavaScript SDK. You should only be using it for things that you're binding to the Angular UI elements. For everything else, you're likely better off using Firebase's regular JavaScript SDK.
If I understand your requirement correctly, you're trying to loop over all child nodes in a database location once and modify a property. If so:
ref.once('value', function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var child = childSnapshot.val();
childSnapshot.ref().update({ lastPoint: child.point - 1 });
});
});
The relevant sections of the Firebase documentation are on reading data once and updating data.
Since AngularFire is built on top of Firebase's JavaScript SDK, they work perfectly together. So if elsewhere you bind the posts to the scope ($scope.posts = $firebaseArray(ref)), they will be updated automatically when you update the last point with the above snippet.
You can create a service that contains a getter and a setter. It would look something like this;
angular.module('app').factory("DataHandler",
function() {
var data;
return {
get: function() {
return data;
},
set: function(something) {
data = something;
}
}
}
);
Then in your code you would call:
var posts = $firebaseArray(ref);
posts.$loaded().then(function(item){
item.forEach(function(childSnapshot){
var num = childSnapshot.point-1;
childSnapshot.lastPoint = num;
DataHandler.set(childSnapshot);
});
});
Then wherever/whenever you need to get that data just call:
Datahandler.get();

Fetching models from the server

I have a RESTful service which have being written using Node.js. If I open http://localhost:5000/links in the browser I will get the collection of links:
[{"_id":"5597f5d3e9a768531c07468a","uri":"http://google.com","title":"google","__v":0,"tags":["one","two"]}]
I need to get this collection from backbone application:
(function () {
var Link = Backbone.Model.extend({});
var LinkCollection = Backbone.Collection.extend({
model: Link,
url: 'http://localhost:5000/links'
});
var links = new LinkCollection();
links.fetch();
console.log(links);
console.log(links.length);
})();
Here is a console:
I can see my object the right side of the console (c3.attributes). But why the length of collection is zero? And how can I get this object?
Classic backbone issue.
Try this:
links.fetch({
success:function(response) {
//here are your results
}
});
Edit: Also I think a collection return a promise so an alternative solution could be:
links.fetch().then(function(response) {
});
haven't use it myself but I think it should work. Hope it helps.

TypeError: undefined is not a function when using Firebase.push()

Following Lynda.com Building a data-driven app with Angularjs.
I am using the MeetingsController to try and push data to Firebase and I'm getting the following error:
TypeError: undefined is not a function
at g.$scope.addMeeting (meetings.js:10)
This points to the meetings.push line
MeetingsController
myApp.controller('MeetingsController', function($scope, $firebaseObject) {
var ref = new Firebase('https://attendanced****.firebaseio.com/meetings');
var meetings = $firebaseObject(ref);
$scope.meetings = meetings;
$scope.addMeeting = function() {
meetings.push({
name: $scope.meetingname,
date: Firebase.ServerValue.TIMESTAMP
}).then(function() {
$scope.meetingname='';
});
}; //addmeeting
});
I have already changed the controller from the course given code due to Firebase removing $firebase and replacing $asObject() with $firebaseObject.
I saw that Firebase was now using .push() instead of .$push().
I did see Question 29053103 which touched on a similar issue but ended with the original poster having to revert to older versions of AngularFire and Firebase to make it work which I'd rather not do.
You can push object to array, but can't push object to object.
I hope that should fixed your app:
...
//I assume that meetings is more then one so that should be $firebaseArray instead of $firebaseObject
$scope.meetings = $firebaseArray(ref);
$scope.addMeeting = function() {
//you can use $add instad of push that will save yoour object to firebase
meetings.$add({
name: $scope.meetingname,
date: Firebase.ServerValue.TIMESTAMP
}).then(function() {
$scope.meetingname='';
});
...
}; //addmeeting

TypeError: undefined is not a function while submitting & deleting post using AngularFire and AngularJS (ThinksterIO Tutorial Chapter 7)

I've run into multiple TypeErrors with the Thinkster.io AngularJS Tutorial: Learn to build Modern Webapps Chapter 7. Creating your own user data using firebase since the tutorial is now outdated after AngularFire was upgraded to v0.8.0. Specifically the .$child() and .$on() methods have been taken out. Here is the change log
https://github.com/firebase/angularfire/releases/tag/v0.8.0
After getting help solving my initial TypeError issues during registering a new user, I began to see 2 new TypeErrors show up when I submit a post and when I try to delete a post. Once again the culprits are the outdated .$child() and .$on() methods.
Submitting a Post > TypeError: undefined is not a function
After submitting a post I see the following TypeError show up in the console
This TypeError points to the post.js service
TypeError: undefined is not a function
at http://localhost:9000/scripts/services/post.js:16:11
which is line 16, column 11 at the beginning of the $child method call. Also, note the second .&child() following the first. That will result in another TypeError.
return posts.$add(post).then(function(ref) {
var postId = ref.name();
user.$child('posts').$child(postId).$set(postId);
return postId;
});
I will mention that even though I get this TypeError, I'm still able to successfully create a post and I see it in the Forge and in the app's post list.
Deleting a Post > TypeError: undefined is not a function
When I try to delete a post that I just created I get another TypeError related to the now deprecated .$on() method.
TypeError: undefined is not a function
at Object.Post [as delete] (http://localhost:9000/scripts/services/post.js:27:10)
at Scope.$scope.deletePost (http://localhost:9000/scripts/controllers/posts.js:10:14)
which points to the .$on() in this code in the post.js service
delete: function(postId) {
if(User.signedIn()) {
var post = Post.find(postId);
post.$on('loaded', function(){
var user = User.findByUsername(post.owner);
posts.$remove(postId).then(function(){
user.$child('posts').$remove(postId);
});
});
}
}
I realize that I will have to do something like
post.$loaded(function(result) {Chapter 7. Creating your own user data using firebase
// something related to finding user of post
// remove post from posts collection
// but of course we can't use .$child()
});
but the problem is that when a JS beginner like me comes along faced with the AngularFire change logs and API, I just get lost and overwhelmed to the point of shut down. Any guidance is greatly appreciated as always.
FILES
post.js service
'use strict';
app.factory('Post', function($firebase, FIREBASE_URL, User){
var ref = new Firebase(FIREBASE_URL + 'posts');
var posts = $firebase(ref).$asArray();
var Post = {
all: posts,
create: function(post) {
if(User.signedIn()) {
var user = User.getCurrent();
post.owner = user.username;
return posts.$add(post).then(function(ref) {
var postId = ref.name();
user.$child('posts').$child(postId).$set(postId);
return postId;
});
}
},
find: function(postId) {
return $firebase(ref.child(postId)).$asObject();
},
delete: function(postId) {
if(User.signedIn()) {
var post = Post.find(postId);
post.$on('loaded', function(){
var user = User.findByUsername(post.owner);
posts.$remove(postId).then(function(){
user.$child('posts').$remove(postId);
});
});
}
}
};
return Post;
});
post.js controller
'use strict';
app.controller('PostsCtrl', function($scope, $location, Post) {
$scope.posts = Post.all;
$scope.post = {url: 'http://', title: ''};
$scope.deletePost = function(post) {
Post.delete(post);
};
});
I was fed up, so I took a easy approach (just to get trough the tutorial). I created userRef (this should come from the User object imo):
modulename.factory("Post", function ($firebase, FIREBASE_URL, User) {
//rest code
var userRef = new Firebase(FIREBASE_URL + "users");
var Post = {
create: function(){
//rest of the code
return posts.$add(post).then(function (ref) {
var postId = ref.name();
userRef.child(user.$id).child("posts").child(postId).set(postId);
return postId;
});
}
}
});
This is just one approach, when I was searching for a good solution, I saw some more example codes. I hope it helps a little bit.

Resources