AngularFire doesn't show data from Firebase Database - firebase

I'm following this video. But I have trouble implementing it. This is the HTML file.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Welcome to Firebase Hosting</title>
<!-- AngularJS -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<!-- AngularFire -->
<script src="https://cdn.firebase.com/libs/angularfire/2.0.2/angularfire.min.js"></script>
<!-- Firebase -->
<script src="https://www.gstatic.com/firebasejs/3.3.0/firebase.js"></script>
<script src="app.js"></script>
</head>
<body ng-app="app">
<div id="message" ng-controller="MyController as ctrl">
<pre>
{{ ctrl.object | json }}
</pre>
</div>
</body>
</html>
And my app.js file is this.
(function(){
// Initialize Firebase
var config = {
apiKey: "SOME KEY",
authDomain: "tier2list.firebaseapp.com",
databaseURL: "https://tier2list.firebaseio.com",
storageBucket: "",
};
firebase.initializeApp(config);
angular.module('app', ['firebase']).controller('MyController', function($firebaseObject){
const rootRef = firebase.database().ref().child('tier2list');
const ref = rootRef.child('object');
this.object = $firebaseObject(ref);
});
}());
This is my database structure.
But the result is as follows.
And there is no errors in the console as well. Database rules are as follows.
{
"rules": {
".read": true,
".write": true
}
}

The problem is in the path you synchronize:
const rootRef = firebase.database().ref().child('tier2list');
There is no child tier2list in your database, so you will get an empty object.
Instead, you're trying to synchronize the entire database, which you can do by:
const rootRef = firebase.database().ref()

I was in the middle of this when Frank answered. He has the right answer, but here is what your database should look like in order to work with David's code:
In his walk through, he is already inside of the angular node, so that could be a little confusing.
I also created a Github repo for the project in case anyone is having trouble making it for themselves:
https://github.com/LukeSchlangen/angularFireQuickDemo

Related

Unable to write data to Firebase realtime database, rules checked

I have problem with writting data to realtime database. I don't know why I can't write anything to database, I checked the database rules and it's allowed to write data
`
var firebaseConfig = {
//key
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
// Database reference
var firebaseRef = firebase.database().ref();
// The click Event
document.getElementById('send').addEventListener('click', function(){
firebaseRef.push(document.getElementById('email').value);
});
<html lang="en">
<head>
<title>Firebase</title>
<script src="https://www.gstatic.com/firebasejs/5.9.3/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.9.3/firebase-database.js"></script>
</head>
<body>
E-mail:<input type="email" id="email">
<button id="send"> Send </button>
<script src="main.js"></script>
</body>
</html>
`

No Firebase App '[DEFAULT]' has been created - Flutter Web project

I'm getting this error when running the project.
It has started after I migrated my project to another Google Account(I had to create all firebase configs(etc) on this account again).
Here is my index.html
<!DOCTYPE html>
<html>
<head>
<!--
If you are serving your web app in a path other than the root, change the
href value below to reflect the base path you are serving from.
The path provided below has to start and end with a slash "/" in order for
it to work correctly.
Fore more details:
* https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base
-->
<base href="/web/">
<meta charset="UTF-8">
<meta content="IE=Edge" http-equiv="X-UA-Compatible">
<meta name="description" content="Foxy Admin Panel">
<!-- iOS meta tags & icons -->
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="apple-mobile-web-app-title" content="Foxy Admin Panel">
<link rel="apple-touch-icon" href="icons/Icon-192.png">
<!-- Favicon -->
<link rel="icon" type="image/png" href="favicon.png"/>
<title>Foxy Admin Panel</title>
<link rel="manifest" href="manifest.json">
</head>
<body>
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/8.9.1/firebase-app.js"></script>
<!-- TODO: Add SDKs for Firebase products that you want to use
https://firebase.google.com/docs/web/setup#available-libraries -->
<script src="https://www.gstatic.com/firebasejs/8.9.1/firebase-analytics.js"></script>
<!-- Firebase Firestore SDK -->
<script src="https://www.gstatic.com/firebasejs/8.4.2/firebase-firestore.js"></script>
<!-- Firebase Messaging SDK -->
<script src="https://www.gstatic.com/firebasejs/8.4.2/firebase-messaging.js"></script>
<!-- Firebase project configuration -->
<script src="https://www.gstatic.com/firebasejs/8.2.4/firebase-firestore.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.2.4/firebase-storage.js"></script>
<!-- This script installs service_worker.js to provide PWA functionality to
application. For more information, see:
https://developers.google.com/web/fundamentals/primers/service-workers -->
<script>
if ('serviceWorker' in navigator) {
window.addEventListener('flutter-first-frame', function () {
navigator.serviceWorker.register('flutter_service_worker.js');
});
}
</script>
<!-- Override the web renderer at runtime: -->
<script type="text/javascript">
// Set your option below
let useHtml = true;
// Check the option value
if(useHtml) {
window.flutterWebRenderer = "html";
} else {
window.flutterWebRenderer = "canvaskit";
}
</script>
<script>
// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getAnalytics } from "firebase/analytics";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: "",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: ""
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
</script>
<script src="main.dart.js" type="application/javascript"></script>
</body>
</html>
https://jsfiddle.net/zeq3L78p/
If I just change the configs from firebase to my old account, it works straightaway.
Do you have any idea what is happening?

Expected a JavaScript module script but the server responded with a MIME type of "text/html"

I have a problem when try to import firebase in my project. Previously i installed firebase dependencies in my project. I'm using ELM-SPA.
Error
My firebase config file:
import firebase from 'firebase/app'
import 'firebase/firestore'
import 'firebase/auth'
import 'firebase/storage'
const firebaseConfig = {
apiKey: "",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: ""
};
//init firebase
firebase.initializeApp(firebaseConfig)
//init services
const projectFirestore = firebase.firestore()
const projectAuth = firebase.auth()
const projectStorage = firebase.storage()
//timestamp
const timestamp = firebase.firestore.FieldValue.serverTimestamp
export{
projectFirestore,
projectAuth,
projectStorage,
timestamp
}
Place where i try to call some firebase functions
import { projectAuth } from '../public/config'
const app = Elm.Main.init({
flags: JSON.parse(localStorage.getItem('storage'))
})
app.ports.save.subscribe(storage => {
localStorage.setItem('storage', JSON.stringify(storage))
app.ports.load.send(storage)
})
My html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/style.css">
<link rel="shortcut icon" href="assets/logo.png" />
</head>
<body>
<script src="/dist/elm.js"></script>
<script type="module" src="/main.js"></script>
</body>
</html>
In main.js you're importing '../public/config', which is what the error is referring to. This is all happening in the browser, so the browser is trying to load that URL and failing. You could change the import to './config.js', but if you have secret information in that config file you shouldn't be exposing it to the public. In that case, you'll need to introduce some server-side component where you store your secrets.
For me, I just had a typo in the name of the component I was trying to render. I was importing and attempting to render approversSettings when the name of the component was actually approverSettings. It was trying to import from approversSettings which did not exist.

"TypeError: undefined is not a function" when trying to push() to Firebase

Upon submission of a form, I want to push that data to my Firebase db and so I'm creating a function to do so (addMeeting). However, upon pressing the button to submit I get the error:
TypeError: undefined is not a function
at l.$scope.addMeeting (http://localhost:8000/js/controllers/meetings.js:10:12)
meetings.js:10:12 is right where my $push is if you'll look at my code below.
My HTML:
<!doctype html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="UTF-8">
<title>Angular Data</title>
<meta name="viewport" content="width=device-width, userscalable=no">
<link rel="stylesheet" href="css/style.css">
<!-- AngularJS -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="js/lib/angular/angular-route.min.js"></script>
<script src="js/lib/angular/angular-animate.min.js"></script>
<!-- Firebase -->
<script src="https://cdn.firebase.com/js/client/2.2.2/firebase.js"></script>
<!-- AngularFire -->
<script src="https://cdn.firebase.com/libs/angularfire/1.0.0/angularfire.min.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers/registration.js"></script>
<script src="js/controllers/meetings.js"></script>
</head>
<body>
<header>
<nav class="cf" ng-include="'views/nav.html'"></nav>
</header>
<div class="page">
<main class="cf" ng-view></main>
</div>
</body>
</html>
My apps.js:
var myApp = angular.module('myApp',
['ngRoute', 'firebase', 'appControllers']);
var appControllers = angular.module('appControllers', ['firebase']);
myApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/login', {
controller: 'RegistrationController',
templateUrl: 'views/login.html'
}).
when('/register', {
controller: 'RegistrationController',
templateUrl: 'views/register.html'
}).
when('/meetings', {
controller: 'MeetingsController',
templateUrl: 'views/meetings.html'
}).
otherwise({
redirectTo: '/login'
});
}])
meetings.js -the Controller containing the addMeeting function that is failing:
myApp.controller('MeetingsController',
function($scope, $firebaseObject) {
var ref = new Firebase('https://angulardataldc.firebaseio.com/meetings');
var meetings = $firebaseObject(ref);
$scope.meetings = meetings;
$scope.addMeeting = function() {
meetings.$push({
name: $scope.meetingname,
date: Firebase.ServerValue.TIMESTAMP
})
}
}); //MeetingsController
The view that is calling that function upon submission of a form:
<section class="meetings cf">
<h1>Add Meetings</h1>
<form class="formgroup addmeeting cf"
name="myform"
ng-submit="addMeeting()"
novalidate>
<div class="inputwrapper">
<input type="text" name="meetingname" placeholder="Meeting Name"
ng-model="meetingname" ng-required="true">
</div>
<button type="submit" class="btn"
ng-disabled="myform.$invalid">+</button>
</form>
<h2>Your Meetings</h2>
<div class="meeting" ng-repeat="meeting in meetings">
<p>{{meeting.name}}</p>
</div>
</section>
**Edit: ** It has something to do with the .push() method itself. I see that in the latest version of angularfire/firebase it should be .push, instead of .$push, ad have changed that but it does not solve my problem. I reverted AngularFire and Firebase to versions 0.8.2 and 1.0.21 respectively, re-introduced the .asObject() and $push, and everything works fine. I don't understand why .push() is failing with all the latest (Firebase 2.2.2, AngularFire 1.0).
Firebase's AngularFire library has two primary types: $firebaseObject and $firebaseArray (instantiated through $asObject and $asArray respectively in pre-1.0 versions of AngularFire).
You're using both the wrong type and the wrong method. To quote AngularFire's documentation on its array type:
Synchronized arrays should be used for any list of objects that will be sorted, iterated, and which have unique IDs. The synchronized array assumes that items are added using $add(), and that they will therefore be keyed using Firebase push IDs.
So:
var ref = new Firebase('https://angulardataldc.firebaseio.com/meetings');
var meetings = $firebaseArray(ref);
$scope.meetings = meetings;
$scope.addMeeting = function() {
meetings.$add({
name: $scope.meetingname,
date: Firebase.ServerValue.TIMESTAMP
})
}
You made a typo, it should be .push instead of $push
CODE
$scope.addMeeting = function() {
meetings.push({
name: $scope.meetingname,
date: Firebase.ServerValue.TIMESTAMP
})
}
Reference

Basic angularjs code not working properly

Have installed the angularjs and Twitter.Bootstrap packages succesfully
This is my index.html:
<!DOCTYPE html>
<html ng-app="TodoApp" xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="Scripts/jquery-1.9.1.js"></script>
<script src="Scripts/bootstrap.js"></script>
<script src="Scripts/angular.js"></script>
<script src="Scripts/angular-resource.js"></script>
<script src="Scripts/app.js"></script>
<link rel="stylesheet" type="text/css" href="Content/bootstrap.css" />
<title>Amazing Todo</title>
</head>
<body>
<div class="container">
<div ng-view></div>
</div>
</body>
</html>
This is my app.js:
var TodoApp = angular.module("TodoApp", []).
config(function ($routeProvider) {
$routeProvider.
when('/', { controller: ListCtrl, templateUrl: 'list.html' }).
otherwise({ redirectTo: '/' });
});
var ListCtrl = function ($scope, $location) {
$scope.test = "testing";
};
And, this is my list.html:
<h1>Test: {{test}}</h1>
This should work fine. However the index.html is not showing the content of list.html. I think the angularjs part is not working properly.
No idea about what am i doing wrong?
Once you have defined a module, you need to define your controllers for that module and not independently.
Thus, your controller should be rewritten as:
TodoApp.controller('ListCtrl', [ '$scope', '$location',
function ($scope, $location) {
$scope.test = "Testing";
}
]);
This should show the view in question.
I would say, that if you check errors in console (in Chrome or IE press F12) you should see:
...Failed to instantiate module TodoApp due to:
Error: [$injector:unpr] Unknown provider: $routeProvider...
The reason for this expectation is that we ask IoC to inject $routeProvider while not correctly listing dependent modules. This is the above code:
var TodoApp = angular
// here we say: we do not need any other module
.module("TodoApp", [])
// here we ask: inject $routeProvider from other module
.config(function ($routeProvider)
So to make it runing we have to include the module 'ngRoute'
var TodoApp = angular
// here we say: we need these modules to make our module working properly
.module("TodoApp", [
'ngRoute'
])
// now we can ask for the provider,
// using minification-safe syntax
.config(
[ '$routeProvider',
function ($routeProvider) {
$routeProvider.
...
}]);
And also do not forget to also reference this module scripts:
<script src="Scripts/angular.js"></script>
<script src="Scripts/angular-resource.js"></script>
<!-- here we have to load this module -->
<script src="Scripts/angular-route.js"></script>
What is your directory structure can you check if list.html is in the same directory as index.html, if not specify a relative path from the application root?
Since no one has posted a full correct answer to this question and it hasn't been closed yet, here is another answer.
This is your function:
var ListCtrl = function ($scope, $location) {
$scope.test = "testing";
};
This is a bare function, which isn't of much use. You need a controller so that Angular knows what to do with {{ test }}:
<div ng-controller="someController">
<h1>{{ test }}</h1>
</div>
If you insist on keeping the function as a separate variable, you could do so and still have a controller:
var ListCtrl = function ($scope, $location) {
$scope.test = "testing";
};
TodoApp.controller('someController', ListCtrl);
This also works.
Despite of this, your UI won't show, as there's an error in it:
var TodoApp = angular.module("TodoApp", [])
You're using $routeProvider and .when(),.otherwise(), for which you need ngRoute as a dependency:
var TodoApp = angular.module("TodoApp", ['ngRoute'])
Your app should work after that.

Resources