Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/30.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular Ionic与Firebase数据库Ref多次调用_Angular_Firebase_Ionic Framework_Firebase Realtime Database_Ionic3 - Fatal编程技术网

Angular Ionic与Firebase数据库Ref多次调用

Angular Ionic与Firebase数据库Ref多次调用,angular,firebase,ionic-framework,firebase-realtime-database,ionic3,Angular,Firebase,Ionic Framework,Firebase Realtime Database,Ionic3,我正在使用Ionic3和AngularFire2与Firebase数据库交互 我有以下代码: ts createMessage(chatItem: any, messageText: string): Promise<firebase.database.ThenableReference> { let offsetRef: firebase.database.Reference = firebase.database().ref(".info/serverTimeOffset

我正在使用Ionic3和AngularFire2与Firebase数据库交互

我有以下代码:

ts

createMessage(chatItem: any, messageText: string): Promise<firebase.database.ThenableReference> {
    let offsetRef: firebase.database.Reference = firebase.database().ref(".info/serverTimeOffset");
    return new Promise<firebase.database.ThenableReference>((resolve) => {
        offsetRef.on("value", (snap: firebase.database.DataSnapshot) => {
            var offset = snap.val();
            var negativeTimestamp = (new Date().getTime() + offset) * -1;

            chatItem.readByReceiver = false;
            if (chatItem && !chatItem.$key && chatItem.key) {
                chatItem.$key = chatItem.key;
            }
            this.updateChat(chatItem);

            let ref: firebase.database.ThenableReference = this.af.database.list('/message').push({
                chatId: chatItem.$key,
                memberId1: this.me.uid,
                memberId2: this.you.uid,
                username: this.me.displayName,
                message_text: messageText,
                timestamp: firebase.database.ServerValue.TIMESTAMP,
                negativtimestamp: negativeTimestamp,
                readByReceiver: false
            });
            resolve(ref);
        });
    });
}
我希望每次调用函数时只执行一次<我认为code>offsetRef.on的行为就像一个可观察的对象

问题

确保代码只执行一次的最佳方法是什么


谢谢。

你说得对,它像一个可观察的物体一样工作,每次值改变时都会被触发。要确保它只运行一次,请使用
one('value')
。 更多信息:


非常感谢。我将测试它。
offsetRef.on("value", (snap: firebase.database.DataSnapshot) => {
    // breakpoint getting executed more than once here
});
offsetRef.once("value").then((snapshot) => {
    // cod will be executed once here
});