火力基地返回快照承诺



我正在使用firebase/firestore,我正在寻找一种方法来回报快照的承诺。

onlineUsers(){
     // i want to return onSnapshot
    return this.status_database_ref.where('state','==','online').onSnapshot();
}

在我做的其他文件中

  componentDidMount(){
    // this.unsubscribe = this.ref.where('state','==','online').onSnapshot(this.onCollectionUpdate) 
    firebaseService.onlineUsers().then(e=>{
        console.log(e)
    })
}

我收到错误

错误:Query.onSnapshot 失败:使用无效参数调用。

类型错误:_firebaseService2.default.取消订阅不是函数

如果我这样做

onlineUsers(){
   return  this.status_database_ref.where('state','==','online').onSnapshot((querySnapshot)=>{
        return querySnapshot
    }) 
}

我得到

TypeError: _firebaseService2.default.onlineUsers(...).then is not a function

另外当我这样做时

   this.unsubscribe = firebaseService.onlineUsers().then((querySnapshot)=>{
        console.log(querySnapshot.size)
        this.setState({count:querySnapshot.size})
    })

其他文件

 onlineUsers(callback) {
    return this.status_database_ref.where('state', '==', 'online').get()
}

不听更改为火力基地,这意味着如果我在火力基地中改变它不会更新或改变大小。

----消防功能---我尝试制作每次更新UserStatus节点时触发的firestore功能,但这需要几秒钟,而且对我来说很慢。

module.exports.onUserStatusChanged = functions.database
.ref('/UserStatus/{uid}').onUpdate((change, context) => {
    // Get the data written to Realtime Database
    const eventStatus = change.after.val();
    // Then use other event data to create a reference to the
    // corresponding Firestore document.
    const userStatusFirestoreRef = firestore.doc(`UserStatus/${context.params.uid}`);

    // It is likely that the Realtime Database change that triggered
    // this event has already been overwritten by a fast change in
    // online / offline status, so we'll re-read the current data
    // and compare the timestamps.
    return change.after.ref.once("value").then((statusSnapshot) => {
        return statusSnapshot.val();
    }).then((status) => {
        console.log(status, eventStatus);
        // If the current timestamp for this data is newer than
        // the data that triggered this event, we exit this function.
        if (status.last_changed > eventStatus.last_changed) return status;
        // Otherwise, we convert the last_changed field to a Date
        eventStatus.last_changed = new Date(eventStatus.last_changed);
        // ... and write it to Firestore.
        //return userStatusFirestoreRef.set(eventStatus);
        return userStatusFirestoreRef.update(eventStatus);
    });
});

计算和更新在线用户计数的功能

module.exports.countOnlineUsers = functions.firestore.document('/UserStatus/{uid}').onWrite((change, context) => {
    const userOnlineCounterRef = firestore.doc('Counters/onlineUsersCounter');
    const docRef = firestore.collection('UserStatus').where('state', '==', 'online').get().then(e => {
        let count = e.size;
        return userOnlineCounterRef.update({ count })
    })
})
JavaScript

中的Promise只能解析(或拒绝(一次。另一方面,onSnapshot可以多次给出结果。这就是为什么onSnapshot不回报承诺的原因。

在当前的代码中,您只剩下一个悬而未决的侦听器来status_database_ref。由于您不对数据执行任何操作,因此继续侦听数据是浪费。

不使用onSnapshot,而是使用get

onlineUsers(callback){
    this.status_database_ref.where('state','==','online').get((querySnapshot)=>{
        callback(querySnapshot.size)
    }) 
}

或者以您原始的方法:

onlineUsers(){
    return this.status_database_ref.where('state','==','online').get();
}
我知道

为时已晚,但这是我使用 TypeScript 和 Javascript 的解决方案。

打字稿

const _db=firebase.firestore;
const _collectionName="users";
    onDocumentChange = (
    document: string,
    callbackSuccess: (currentData: firebase.firestore.DocumentData, source?: string | 'Local' | 'Server') => void,
    callbackError?: (e: Error) => void,
    callbackCompletion?: () => void
) => {
    this._db.collection(this._collectionName).doc(document).onSnapshot(
        {
            // Listen for document metadata changes
            includeMetadataChanges: true
        },
        (doc) => {
            const source = doc.metadata.hasPendingWrites ? 'Local' : 'Server';
            callbackSuccess(doc.data(), source);
        },
        (error) => callbackError(error),
        () => callbackCompletion()
    );
};

JAVASCRIPT (ES5(

var _this = this;
onDocumentChange = function (document, callbackSuccess, callbackError, callbackCompletion) {
    _this._db.collection(_this._collectionName).doc(document).onSnapshot({
        // Listen for document metadata changes
        includeMetadataChanges: true
    }, function (doc) {
        var source = doc.metadata.hasPendingWrites ? 'Local' : 'Server';
        callbackSuccess(doc.data(), source);
    }, function (error) { return callbackError(error); }, function () { return callbackCompletion(); });
};

我找到了一种方法来做到这一点

onlineUsers(callback){
   return  this.status_database_ref.where('state','==','online').onSnapshot((querySnapshot)=>{
        callback(querySnapshot.size)
    }) 
}
componentDidMount(){
    this.unsubscribe = firebaseService.onlineUsers(this.onUpdateOnlineUsers);
    console.log(this.unsubscribe)
}
onUpdateOnlineUsers(count){
    this.setState({count})
}
componentWillUnmount(){
    this.unsubscribe();
}

最新更新