![](/img/trans.png)
[英]How can I fire an app-wide event in Angular2 or observe a global variable
[英]How do I implement a app-wide notification feature when there is a change in my Firestore collection in Ionic 3?
我目前正在開發一個ionic 3項目,其中實現了一個聊天功能。 我使用firebase firestore作為我的數據庫。
我的目標是實現一個app-wide notification
功能,該功能在firestore chat collection
創建新消息時觸發,但我在嘗試實現這一目標時遇到了一些困難。
這是我的 :
this.chat = this.firestoreProvider.getChatRooms(userEmail).valueChanges();
this.chat.subscribe(res=>{
// Triggered when there are changes in the firestore chat room collection
});
這是我的firestoreProvider
的代碼塊:
getChatRooms(chatRoomOwnerEmail:string){
return this.firestore.collection("Chat Room", ref => ref.where("chatRoomOwnerEmail", "==", chatRoomOwnerEmail).orderBy("chatRoomLastMessage", "asc"));
}
我試圖將此方法放在我的app.component.ts 中,但是當我執行ionic serve
時它使我的整個應用程序崩潰。
是否有關於如何使用在我的應用程序中的所有頁面觸發的firestore
實現此實時notification
功能的解決方案? (意味着在所有頁面中,聊天室中的新消息檢查將繼續觸發)。
更新:
我設法獲得了real-time notification
,但現在我需要在有通知時在主頁上做一些事情。 關於如何做到這一點的任何建議?
好吧,由於您使用的是ionic
,您可以使用托管ion-nav
的AppComponent
來監聽更改。 然后在收到回復時舉杯慶祝。
這樣,即使視圖發生變化, AppComponent
仍會在視圖上,並且仍會監聽變化。
在這里,試試這個:
import { Component } from "@angular/core";
import { Platform } from "ionic-angular";
import { Subscription } from "rxjs";
import { ToastController } from "ionic-angular";
import { TabsPage } from "../pages/tabs/tabs";
import { DataService } from "./data.service";
@Component({
templateUrl: "app.html"
})
export class MyApp {
rootPage: any = TabsPage;
changeSubscription: Subscription;
constructor(
platform: Platform,
private dataService: DataService,
public toastController: ToastController
) {
platform.ready().then(() => {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
});
}
ngOnInit() {
this.changeSubscription = this.dataService
.listenForChange()
.subscribe(response => {
const toast = this.toastController.create({
message: "Data Changed!",
duration: 3000
});
toast.present();
});
}
ngOnDestroy() {
this.changeSubscription.unsubscribe();
}
}
注意:我在答案中使用了 Ionic V3 語法,因為 StackBlitz 沒有 V4 ATM 的模板。 如果您使用的是 V4,則語法可能會略有變化。
您可能也不想
subscribe
Observable
,而是在模板中使用帶有async
管道的Observable
。 這樣你就可以避免任何內存泄漏。 我訂閱了Observable
因為我必須展示吐司。這是您的參考的工作示例代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.