Unable to add data into Firebase - firebase

Im getting the following two errors when trying to upload my JSON into Firebase:
Console error
Factory:
angular
.module("ngClassifieds")
.factory("classifiedsFactory", function($http, $firebaseArray){
(
var ref = new Firebase('https://xxxxx.firebaseio.com/');
return {
ref: $firebaseArray(ref)
}
});
Controller:
.controller("classifiedsCtrl", function($scope, $http, classifiedsFactory, $mdSidenav, $mdToast, $mdDialog)
I am using the following code to upload my JSON into firebase.
var firebase = classifiedsFactory.ref //we have a variable pointing to our classifiedsFactory reference
angular.forEach(data, function (item) {
firebase.$add(item);
});
Please let me know where I'm going wrong here.

Related

How do I make a firestore query to be used with both get() and valueChanges()?

I am using Angular 8 and have a form where a user can choose what he wants to query the database for and then click either of two buttons - one to view data in realtime on the website, and the other to download the data.
I thought I could make use of one function to make a query and then call different functions depending on what button the user clicked, using get() for the download and valueChanges() for the realtime data view. But when I try this, I get the following errors in the browser console. (This is with query as type any - if I specify the type as AngularFirestoreCollection I get errors regarding my type for the get() part in VSCode)
ERROR Error: "Uncaught (in promise): TypeError: this.query.get is not
a function
I can add that I previously had two completely separate (working) functions for downloading and viewing in realtime. And for downloading I used the below query. I gather this is actually a Firestore Query, whereas the "query" I'm trying to use in my updated code is an AngularFirestoreCollection. But is there a way I can make some kind of Query/Collection that will work for both get() and valueChanges()?
Old (working) query:
var query = this.afs.collection(collection).ref.where('module', 'in', array_part);
Trying a common function makeQuery():
onSubmit(value, buttonType): void {
if (buttonType=='realtime') {
this.getRealTimeData(value);
}
if (buttonType=='download') {
this.downloadCsv(value);
}
}
async downloadCsv(value) {
this.query = this.makeQuery(value);
this.dataForDownload = await this.getDataForDownload();
this.dataForDownload = JSON.stringify(this.dataForDownload['data']);
console.log('Data: ', this.dataForDownload);
var date = new Date();
var date_str = this.datePipe.transform(date, 'yyyy-MM-ddTHH-mm');
this.makeFileService.downloadFile(this.dataForDownload, 'OPdata-' + date_str);
}
getDataForDownload() {
return this.query.get()
.then(function (querySnapshot) {
var jsonStr = '{"data":[]}';
var dataObj = JSON.parse(jsonStr); //making object we can push to
querySnapshot.forEach(function (doc) {
JSON.stringify(doc.data()), ', id: ', doc.id);
dataObj['data'].push(doc.data());
});
return dataObj;
})
.catch(function (error) {
console.log("Error getting documents: ", error);
});
}
async getRealTimeData(value) {
this.query = await this.makeQuery(value);
this.data = this.query.valueChanges();
}
async makeQuery(value) {
var collection: string;
return this.query = this.afs.collection<DataItem>('CollectionName', ref => ref.where('datetime', '>=', '2020-01-15T09:51:00.000Z').orderBy('datetime', 'desc').limit(100));
}
The valueChanges() is a method used in angularfire to retrieve data from firestore, while the get() method is used to retrieve from firestore but using the vanilla javascript.
Mixing both methods will return an error as you have seen in your code. Therefore, since angularfire was created above the javascript firebase code, then you should be able to use valueChanges() to view data in realtime on the website, and to download the data.

Mongodb insert call not working inside the server

I am sure I am making something essentially quite wrong, hope someone can help me here.
I have my mongo model defined in my /my_project/lib/collections/item.js
This file has:
import { Mongo } from 'meteor/mongo';
const Item = new Mongo.Collection('item', {connection: null});
export default Item;
Then, I have my /my_project/server/server.js which is:
var log4js = require('log4js');
var logger = log4js.getLogger();
var Item = require('../lib/collections/item.js');
function calculate(params) {
... //removed for brevity
Item.insert({
key:'key',
percentage:profit_in_pct,
createdAt: new Date() // current time
});
}
And the error I am getting is:
I20170925-12:09:03.457(10)? Exception in callback of async function:
TypeError: Item.insert is not a function
I20170925-12:09:03.458(10)? at Object.calculate
(server/server.js:25:8) I20170925-12:09:03.459(10)? at
runWithEnvironment (packages/meteor.js:1189:24)
Any help will be much appreciated. Thanks

Adding photos from Instragram API to synchronized array in AngularFire

I built a simple Instagram app using the Instagram API and Angular.
Now I would like to permanently store the users search (aka response from Instagram server for each hashtag entered) to Firebase.
I got the Instagram API call working and saved it as $scope.instadata but how do I add $scope.instadata to Firebase using $add()?
I'm getting err:
angular.js:11500 Error: Firebase.set failed: First argument contains a function..
var app = angular.module('InstagramApp', ['firebase']);
app.controller('MainController', function ($scope, $http, $firebaseArray) {
// search posts based on hashtag
function getHash() {
var base = 'https://api.instagram.com/v1/tags/'
var service = document.getElementById('hashtag').value
var apiKey = '####'
var callback = 'JSON_CALLBACK'
var url = base + service + '/media/recent?access_token=' + apiKey + '&callback=' + callback
// use jsonp method to prevent CORS error
$http.jsonp(url).then(function(data) {
$scope.instadata = data
console.log("returned json object: ")
console.log($scope.instadata)
// set up firebase reference
var ref = new Firebase('https://myapp.firebaseio.com/fbdata')
// create a synchronized array
$scope.fbdata = $firebaseArray(ref)
// add new items to the array RETURNS ERROR
$scope.fbdata.$add($scope.instadata).then(
function(p){
console.log(p.key())
console.log($scope.instadata)
},
function(err){
console.log("The expected Firebase action failed to occur this was your error: " + err)
})
}
 })
}
document.getElementById('hashtag').addEventListener('click', getHash, false)
})
It's my first time asking a question here, working with API's, Angular and Firebase! I hope that's ok!

Polymer using firebase query with context

in my custom Polymer element, i have a method that queries a firebase instance like so:
_updateUser: function(user) {
if(this._firebaseRef) {
this._firebaseRef.off()
}
if(user) {
var userLocation = ['xxxxx.firebaseio.com', 'users', this.user.uid].join('/');
this._firebaseRef = new Firebase(userLocation);
var query = this._firebaseRef.orderByChild("username")
query.on("value", function(messageSnapshot) {
messageSnapshot.forEach(function(messageData){
this.set('usernames', []);
console.log(this);
});
},null, this);
}
},
However, I keep getting the following error Uncaught TypeError: this.set is not a function. It seems that this is not set as the context as expected as per the api documentation
May I know how I can call this.set in my callback successfully? Thanks.
You need to pass the context into the forEach function as well.
messageSnapshot.forEach(function (messageData) {...}, this)
or
messageSnapshot.forEach(function (messageData) {...}.bind(this))

meteor collection - leaderboard app

What am i doing wrong?
I'm building the leaderboard app from meteortips.com
Trying to build a collection in the database this is my code:
new Meteor.Collection('players');
PlayersList = new Meteor.Collection('players');
if(Meteor.isClient) {
console.log("Hello Client");
}
if(Meteor.isServer) {
console.log("Hello Server");
}
Trying out PlayersList on the js console gives me an error:
PlayersList
ReferenceError: PlayersList is not defined
message: "PlayersList is not defined"
stack: (...)
stack: function () { [native code] }
set stack: function () { [native code] }
proto: Error
You’re defining the collection twice. Change:
new Meteor.Collection('players');
PlayersList = new Meteor.Collection('players');
to just:
PlayersList = new Meteor.Collection('players');
you must to create the collection of follows way
PlayersList = new Meteor.Collection('players');
and you have to pay attention where you create this collection, because if you want have this collection in the two sides, client and server, you must create the collection in one archive outside of client and server folder. This collection you can use in all your application.

Resources