发送消息时获取ID - Firebase& AngularFire

时间:2017-08-19 03:16:20

标签: javascript firebase firebase-realtime-database

我有一个消息" app"我需要在创建消息时获取ID。 以下是所有代码:

<html ng-app="sampleApp">

<body ng-controller="SampleCtrl">
    <ul>
        <li ng-repeat="message in messages">
            <input ng-model="message.message" ng-change="messages.$save(message)" />
            <input ng-model="message.by" ng-change="messages.$save(message)" />
            <button ng-click="messages.$remove(message)">Delete Message</button>
        </li>
    </ul>
    <form ng-submit="addMessage()">
        <input ng-model="newMessageText" />
        <input ng-model="newMessageBy" />
        <button type="submit">Add Message</button>
    </form>

    <!-- Angular -->
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>

    <!-- Firebase -->
    <script src="https://www.gstatic.com/firebasejs/3.6.6/firebase.js"></script>

    <!-- AngularFire -->
    <script src="https://cdn.firebase.com/libs/angularfire/2.3.0/angularfire.min.js"></script>
    <script>
        var config = {
            apiKey: "xxx",
            authDomain: "xxx",
            databaseURL: "xxx",
            projectId: "xxx",
            storageBucket: "xxx",
            messagingSenderId: "xxx"
        };
        firebase.initializeApp(config);
        var app = angular.module("sampleApp", ["firebase"]);
        app.controller("SampleCtrl", function ($scope, $firebaseArray) {
            var ref = firebase.database().ref().child("messages");
            $scope.messages = $firebaseArray(ref);
            $scope.addMessage = function () {

                $scope.messages.$add({
                    message: $scope.newMessageText,
                    by: $scope.newMessageBy
                });
            };
        });
    </script>
</body>

</html>

发送邮件时,会在其下创建ID及邮件内容。因此,我需要获取已发送邮件的ID,并将ID写入Firebase。

这是数据库的样子:

{
  "messages" : {
    "-KrsHPUi7pIWTQ1qgO4q" : { // I NEED TO GET THIS
      "message": "blah blah blah...",
      "by": "john"
    }
  },
  "ids" : {
    "first": "-KrsHPUi7pIWTQ1qgO4q" // AND PUT IT HERE
}

1 个答案:

答案 0 :(得分:1)

在这里你如何获得id

$scope.messages.$add({
                    message: $scope.newMessageText,
                    by: $scope.newMessageBy
                }).then(function(ref) {
                   var id = ref.key;
                  // do with the key what ever you want
})