簡體   English   中英

Firebase + Cloud功能動態onCall

[英]Firebase + Cloud functions dynamic onCall

我正在使用angular / firebase網絡應用程序,並且開始在onCall上創建雲函數。

我的應用基於聊天室:

messages
    |__1
       |__ 0
           |__ author: "foo"
           |__ message: "hello world"
           |__ playerExcluded: "foo2"
       |__ 1
           |__ author: "foo2"
           |__ message: "hello world"
           |__ playerExcluded: "foo"

我想列出currentUser!= playerExluded的所有消息(用戶可以看到除他以外的消息以外的所有消息),這就是為什么我開始尋找雲功能的原因。 在執行此操作之前,我只是先嘗試​​一些操作,但並沒有達到我想要的效果。

這是我寫的:

雲功能:

const getMessages = functions.https.onCall((data, context) => {
    console.log('data: ', data);
    return new Promise((resolve, reject) => {
        admin.database().ref('/messages').child(data).on('value', msg => {
            resolve(msg.val());
        });
    })
});

module.exports = { getMessages };

(我使用Promise是因為沒有它,它什么也不會返回。我使用.on而不是.once是因為我需要動態獲取消息)。

角部分:

服務:

messages: Message[] = [];
messagesSubject = new Subject<Message[]>();

getMessages() {
    firebase.functions().httpsCallable("getMessages")("1").then(result => {
        console.log("result: ", result);
        this.messages = [result.data[0]]; // let's try with first message
        console.log(this.messages);
        this.emitMessages();
    }).catch(error => {
        console.log("error:", error);
    });
}
emitMessages() {
    this.messagesSubject.next(this.messages);
}

零件:

messages;
messagesSubscription: Subscription;

constructor(private messageService: MessageService) { }

ngOnInit() {
    this.messageService.getMessages();
    this.messagesSubscription = this.messageService.messagesSubject.subscribe((result) => {
        console.log(result);
        this.messages = result;

    });
}

一切都會好起來的。 但這不是動態的,我需要刷新頁面以查看更改。

我做錯什么了嗎 ? Firebase查詢“ .on”是否與雲函數.onCall和httpsCallable不兼容(如果是,則有任何建議嗎?)?

您不能使用可調用函數來提供持續的結果。 您必須從onCall返回一組結果,然后函數終止。 如果需要更多更新,則必須再次調用該函數,但最好是客戶端可以使用Firebase SDK直接查詢數據庫並在結果更改時偵聽結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM