简体   繁体   中英

How to connect to Firebase

I am trying to connect to Firebase using AngularJS.

I know I have to set config info etc. But I don't know where and how.

Where can I put and sync my config in my codes?

Saying my config is like this:

  firebase.initializeApp(config);

Here are my codes :

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Test1 with Angular1</title>
    <!-- Angular -->
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>

    <!-- Firebase -->
    <script src="https://cdn.firebase.com/js/client/2.2.4/firebase.js"></script>

    <!-- AngularFire -->
    <script src="https://cdn.firebase.com/libs/angularfire/1.2.0/angularfire.min.js"></script>
    <script>
        var app = angular.module("app",["firebase"]);
        app.controller("myController",["$scope","$firebaseObject",function($scope,$firebaseObject){

            var ref = new Firebase(<url>);
        }]);
    </script>
</head>
<body>
    <div class="container" ng-app="app" ng-controller="myController">
        {{ 1+1 }}
    </div>
</body>
</html>
  1. Create a new file(just to keep things clean), call this firebase-config.js
  2. Add your config to the file

     var config = { apiKey: "AIzaSyBrPs1GLV-0APAs_3PFpvldGbcgE-eVYY", authDomain: "letsayone.firebaseapp.com", databaseURL: "https://letsayone.firebaseio.com", storageBucket: "letsayone.appspot.com", messagingSenderId: "175605985282" }; firebase.initializeApp(config); 

3 Now add the js file to your index.html, before your controller codes.

....
<script src="https://cdn.firebase.com/libs/angularfire/1.2.0/angularfire.min.js"></script>
<script src="firebase-config.js"></script>
<script>...your controller codes here</script>

Note you should be using the latest version of firebase. 3.xx Firebase documentation

Something really confuses me about your question, you are using the 2.0 SDK, and at the same time config files which I think is a 3.0 feature? Correct me if Im wrong!

First of all, try to stay away from the new operator. Its not nice for unit testing.

Its a better way to use constants and angular services.

 app
    .constant('firebaseUrl', "https://letsayone.firebaseio.com")
    .service('rootRef', ['firebaseUrl', Firebase])

In your controller, you want to inject rootRef

app.
    controller('mainCtrl', ['$scope', 'rootRef', function($scope, rootRef){ 
}])

Also don't forget to inject firebaseObject or firebaseArray depending on the one you are going to use!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM