我正在使用ionic2和firebase。
这是我的应用组件。
import { Component, ViewChild,Inject } from '@angular/core';
import { Nav,NavController,Platform ,AlertController,MenuController,App,IonicApp} from 'ionic-angular';
import { Splashscreen ,Network,Toast,LocalNotifications} from 'ionic-native';
import { ComplaintsPage } from '../pages/complaints/complaints';
import { MycomplaintsPage } from '../pages/mycomplaints/mycomplaints';
import { ChatlistPage } from '../pages/chatlist/chatlist';
import { LoginPage } from '../pages/login/login';
import { IndexPage } from '../pages/index/index';
import { Authservice } from '../providers/authservice';
import { NeighboursPage } from '../pages/neighbours/neighbours';
import { NotificationsPage } from '../pages/notifications/notifications';
import { UpdateprofilePage } from '../pages/updateprofile/updateprofile';
import { DirectoryPage } from '../pages/directory/directory';
import { TabsPage } from '../pages/tabs/tabs';
import { SettingsPage } from '../pages/settings/settings';
import { EventPage } from '../pages/event/event';
import { PropertyPage } from '../pages/property/property';
import { AlbumPage } from '../pages/album/album';
import { VisitorsPage } from '../pages/visitors/visitors';
import { ExpectedvisitorsPage } from '../pages/expectedvisitors/expectedvisitors';
import { CircularPage } from '../pages/circular/circular';
import { DashboardPage } from '../pages/dashboard/dashboard';
import { AlarmPage } from '../pages/alarm/alarm';
import { AlarmdetailsPage } from '../pages/alarmdetails/alarmdetails';
import { StatusBar } from '@ionic-native/status-bar';
import { FormBuilder } from '@angular/forms';
import { AngularFire } from 'angularfire2';
declare var navigator: any;
declare var Connection: any;
declare var window: any;
declare var FCMPlugin;
declare var Media:any;
export interface PageInterface {
title: string;
component: any;
logsOut?: boolean;
icon?:string;
}
interface /*PhoneGapNavigator extends*/ Navigator {
app: any;
}
@Component({
templateUrl: 'app.html'
})
export class MyApp {
audio;
public app: App;
currentuser;
@ViewChild(Nav) nav1: Nav;
auth:any;
menu;
nav:NavController;
rootPage:any = LoginPage;
loginPages:PageInterface[]=[
{ title: 'Login', component: LoginPage }
];
showRoot = false;
ApartID;
USERID;
EMERGENCY;
logo;
Apartmentname;
logoutpages :PageInterface[] = [
{ title: 'Dashboard', component: DashboardPage, icon:'dashboard.svg'},
{ title:'Emergency',component:AlarmPage,icon:'alarm.svg'},
{ title:'Albums',component:AlbumPage, icon:'album.svg' },
{ title: 'Repairs', component: MycomplaintsPage, icon:'complaints.svg'},
{ title:'My Neighbours',component:NeighboursPage, icon:'neighbours.svg'},
{ title:'Notifications',component:NotificationsPage, icon:'notification.svg'},
{ title:'Directory',component:TabsPage, icon:'directory.svg'},
{ title:'Chats',component:ChatlistPage, icon:'chat.svg'},
{ title:'Community News',component:CircularPage, icon:'circullar.svg'},
{ title:'Amneties Booking',component:EventPage, icon:'booking.svg'},
{ title:'Visitors',component:VisitorsPage, icon:'visitor.svg'},
{ title:'Property',component:PropertyPage, icon:'buy_sell.svg'},
{ title:'Settings',component:SettingsPage, icon:'settings.svg'},
{ title: 'LogOut',component:LoginPage,logsOut:true, icon:'logout.svg'}
];
managementuser:PageInterface[] = [
{ title: 'Dashboard', component: DashboardPage, icon:'dashboard.svg'},
{ title:'Emergency',component:AlarmPage,icon:'alarm.svg'},
{ title:'Albums',component:AlbumPage, icon:'album.svg' },
{ title: 'Repairs', component: MycomplaintsPage, icon:'complaints.svg'},
{ title:'My Neighbours',component:NeighboursPage, icon:'neighbours.svg'},
{ title:'Notifications',component:NotificationsPage, icon:'notification.svg'},
{ title:'Directory',component:TabsPage, icon:'directory.svg'},
{ title:'Chats',component:ChatlistPage, icon:'chat.svg'},
{ title:'Community News',component:CircularPage, icon:'circullar.svg'},
{ title:'Amneties Booking',component:EventPage, icon:'booking.svg'},
{ title:'Visitors',component:VisitorsPage, icon:'visitor.svg'},
{ title:'Property',component:PropertyPage, icon:'buy_sell.svg'},
{ title:'Settings',component:SettingsPage, icon:'settings.svg'},
{ title: 'LogOut',component:LoginPage,logsOut:true, icon:'logout.svg'}
];
userrole:PageInterface[] = [
{ title:'Property',component:PropertyPage, icon:'buy_sell.svg'},
{ title:'Settings',component:SettingsPage, icon:'settings.svg'},
{ title: 'LogOut',component:LoginPage,logsOut:true, icon:'logout.svg'}
]
constructor(public af:AngularFire,public fb:FormBuilder,private Status:StatusBar,public appCtrl: App,public menu1: MenuController,public alertCtrl:AlertController,public platform: Platform,public authservice:Authservice) {
this.auth=localStorage.getItem("email");
var roleid=localStorage.getItem('Roleid');
console.log("Auth"+this.auth);
if(this.auth != undefined && this.auth != null)
{
this.authservice.getcurrentuserID().first().subscribe(
data=>{
var apartid=data[0].APART_ID;
this.authservice.getallapartments(apartid).subscribe(
data=>{
this.logo=data[0].APART_LOGO;
this.Apartmentname=data[0].APART_NAME;
console.log(this.logo);
})
})
}
if(this.auth != undefined && this.auth != null)
{
if(roleid === '3' || roleid === '4')
{
this.rootPage = DashboardPage;
}
if(roleid === '2' || roleid === '5')
{
this.rootPage = DashboardPage;
}
if(roleid === '6')
{
this.rootPage = PropertyPage;
}
}
this.platform.ready().then(() => {
var url='https://firebasestorage.googleapis.com/v0/b/apartments-ea9e5.appspot.com/o/Loud-Ringtone-11-Emergency-Alert.mp3?alt=media&token=7d67b437-e96b-484e-bd97-008106a06dcb';
this.audio = new Media(url,
// success callback
function () { console.log("playAudio():Audio Success"); },
// error callback
function (err) { console.log("playAudio():Audio Error: " + err); },
function(statusCallback){console.log("Status"+statusCallback)}
);
})
this.showRoot = true;
this.initializeApp();
}
initializeApp() {
this.platform.ready().then(() => {
this.platform.pause.subscribe(() => {
console.log('[INFO] App paused');
console.log("backround");
localStorage.setItem("apprunning",'paused');
});
this.platform.resume.subscribe(() => {
console.log('[INFO] App resumed');
console.log("foreground");
localStorage.setItem("apprunning",'resumed')
});
let self = this;
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
// this.Status.styleDefault();
this.Status.backgroundColorByHexString("#0e5591");
this.hideSplashScreen();
this.platform.registerBackButtonAction(() => {
//window.plugins.toast.show("Press again to exit", "short",'center',2000);
if (this.nav1.canGoBack()) {
console.log('nav can go back');
this.getActivePage();
var page1=localStorage.getItem('email');
var page2=localStorage.getItem('page');
if( page2 != 'LoginPage')
{
console.log("page2 :"+page2);
console.log("goto back success");
this.nav1.pop();
}
if(page2 == 'LoginPage')
{
console.log("page2 :"+page2);
console.log("goto back failed then exit to app");
this.exit();
}
}
else{
console.log("exit");
this.exit();
}
})
//Push Notifications
if(typeof(FCMPlugin) !== "undefined")
{
FCMPlugin.getToken(function(t){
console.log("Use this token for sending device specific messages\nToken: " + t);
}, function(e){
console.log("Uh-Oh!\n"+e);
});
FCMPlugin.onNotification(function(d){
if(d.wasTapped){
console.log(d);
var nav=self.appCtrl.getRootNav().setRoot(NotificationsPage);
} else {
// Foreground receival, update UI or what have you...
console.log("Push Notification", d);
window.plugins.toast.show("You have new notifications", "short",'bottom',1500);
console.log("you have new notifications");
}
}, function(msg){
console.log("msg");
console.log(msg);
// No problemo, registered callback
}, function(err){
console.log("Arf, no good mate... " + err);
});
}
if(Network.type === Connection.NONE)
{
console.log("success");
let alert = this.alertCtrl.create({
title: "Internet Connection",
subTitle:"Please Check Your Network connection",
buttons: [
{
text: 'Ok',
handler: () => {
this.platform.exitApp();
}
}
]
});
alert.present();
}
});
}
openPage(page) {
// Reset the content nav to have just this page
// we wouldn't want the back button to show in this scenario
// this.authservice.getLoggedInUser();
this.nav1.setRoot(page.component);
if (page.logsOut === true) {
this.authservice.logout();
localStorage.clear();
}
}
isUserLoggedIn():boolean {
let user = this.authservice.getcurrentuser();
this.currentuser=localStorage.getItem('Roleid');
// console.log(this.currentuser);
// console.log(typeof(this.currentuser));
return user !== null;
}
check():any
{
this.authservice.checkRole().subscribe(data=>{
this.currentuser=data[0].ROLE_ID;
console.log(this.currentuser)
console.log(typeof(this.currentuser));
})
}
exit(){
let alert = this.alertCtrl.create({
title: 'Confirm',
message: 'Do you want to exit?',
buttons: [{
text: "Ok",
handler: () => { this.exitApp() }
}, {
text: "Cancel",
role: 'cancel'
}]
})
alert.present();
}
//App exit
exitApp(){
this.platform.exitApp();
}
//Splashscreen hide
hideSplashScreen() {
if(navigator && navigator.splashscreen) {
setTimeout(()=> {
navigator.splashscreen.hide();
}, 500);
}
}
getActivePage() {
//var val= this.nav1.getActive().name;
var val=this.nav1.getPrevious().name;
console.log("val");
console.log(val);
localStorage.setItem('page',val);
}
Backroundnotifications()
{
//Get Current UserID
var roleid1=localStorage.getItem('Roleid');
this.authservice.getcurrentuserID().subscribe(
data=>{
console.log(data);
this.ApartID=data[0].APART_ID;
this.USERID=data[0].USER_ID;
this.EMERGENCY=[];
if(roleid1 === '2' || roleid1 === '5')
{
this.authservice.GetEmergencytype(this.ApartID).subscribe(d=>{
var EM=d;
this.EMERGENCY=EM.filter(a=>a.FROM.toString() != this.USERID.toString());
console.log("EMERGENCY");
var emergencyval=this.EMERGENCY.filter(d=>d.STATUS == 'ON');
console.log("TYPE");
console.log(emergencyval);
// if(emergencyval.length != 0)
// {
// if(emergencyval[0].STATUS === "ON")
// {
// var e=emergencyval[0];
// var key=emergencyval[0].$key;
// // this.schedule(e);
// // LocalNotifications.on("click", (notification, state) => {
// // this.audio.stop();
// // this.nav1.setRoot(AlarmdetailsPage);
// // });
// }
// }
})
}
})
}
Foregroundnotifications()
{
//Get Current UserID
this.audio="";
var roleid1=localStorage.getItem('Roleid');
this.authservice.getcurrentuserID().subscribe(
data=>{
console.log(data);
this.ApartID=data[0].APART_ID;
this.USERID=data[0].USER_ID;
this.EMERGENCY=[];
if(roleid1 === '2' || roleid1 === '5')
{
this.authservice.GetEmergencytype(this.ApartID).subscribe(d=>{
var EM=d;
this.EMERGENCY=EM.filter(a=>a.FROM.toString() != this.USERID.toString());
console.log("EMERGENCY");
var emergencyval=this.EMERGENCY.filter(d=>d.STATUS == 'ON');
console.log("TYPE");
console.log(emergencyval);
if(emergencyval.length != 0)
{
if(emergencyval[0].STATUS === "ON")
{
this.platform.ready().then(() => {
window.plugins.toast.show("Emergency notifications", "short",'bottom',3000);
});
}
}
})
}
})
}
schedule(a)
{
console.log("receive Notification")
var val=a;
var t:any=a.MSG;
var time:any=a.SEND_TIME;
LocalNotifications.schedule({
title: "Smart Premises",
text: t,
at: time,
sound:this.playSelectedTrack(),
});
}
playSelectedTrack():any{
console.log("audio play");
this.audio.play();
}
}
这是我的dashboard.ts
import { Component } from '@angular/core';
import { NavController, NavParams ,Platform} from 'ionic-angular';
import { LocalNotifications,Toast} from 'ionic-native';
import { FirebaseAuth, AuthProviders, AuthMethods} from 'angularfire2';
import { Authservice } from '../../providers/authservice';
import { AlbumPage } from '../../pages/album/album';
import { MycomplaintsPage } from '../../pages/mycomplaints/mycomplaints';
import { NeighboursPage } from '../../pages/neighbours/neighbours';
import { NotificationsPage } from '../../pages/notifications/notifications';
import { ChatlistPage } from '../../pages/chatlist/chatlist';
import { TabsPage } from '../../pages/tabs/tabs';
import { CircularPage } from '../../pages/circular/circular';
import { EventPage } from '../../pages/event/event';
import { SettingsPage } from '../../pages/settings/settings';
import { VisitorsPage } from '../../pages/visitors/visitors';
import { AlarmPage } from '../../pages/alarm/alarm';
import { AlarmdetailsPage } from '.././alarmdetails/alarmdetails';
import { PropertyPage } from '../../pages/property/property';
import { FormBuilder } from '@angular/forms';
import { AngularFire } from 'angularfire2';
declare var Media:any;
declare var window: any;
/*
Generated class for the Dashboard page.
See http://ionicframework.com/docs/v2/components/#navigation for more info on
Ionic pages and navigation.
*/
@Component({
selector: 'page-dashboard',
templateUrl: 'dashboard.html'
})
export class DashboardPage {
EMERGENCY=[];
ApartID;
USERID;
audio;
audioplaying;
constructor(public af:AngularFire,public fb:FormBuilder,public platform: Platform,public authservice:Authservice,public navCtrl: NavController, public navParams: NavParams, public auth: FirebaseAuth) {
this.platform.ready().then(() => {
var url='https://firebasestorage.googleapis.com/v0/b/apartments-ea9e5.appspot.com/o/Loud-Ringtone-11-Emergency-Alert.mp3?alt=media&token=7d67b437-e96b-484e-bd97-008106a06dcb';
this.audio = new Media(url,
// success callback
function () { console.log("playAudio():Audio Success"); },
// error callback
function (err) { console.log("playAudio():Audio Error: " + err); },
function(statusCallback){console.log("Status"+statusCallback)
this.audioplaying = statusCallback;
localStorage.setItem("audioplaying",this.audioplaying);
}
);
})
}
ionViewDidLoad() {
console.log('ionViewDidLoad DashboardPage');
this.Backroundnotifications();
}
albums() {
this.navCtrl.push(AlbumPage);
}
complaints() {
this.navCtrl.push(MycomplaintsPage);
}
myNeighbours() {
this.navCtrl.push(NeighboursPage);
}
notification() {
this.navCtrl.push(NotificationsPage);
}
chats() {
this.navCtrl.push(ChatlistPage);
}
directory() {
this.navCtrl.push(TabsPage);
}
circular() {
this.navCtrl.push(CircularPage);
}
eventbooking() {
this.navCtrl.push(EventPage);
}
settings() {
this.navCtrl.push(SettingsPage);
}
visitors() {
this.navCtrl.push(VisitorsPage);
}
propertyPage() {
this.navCtrl.push(PropertyPage);
}
alarmPage() {
this.navCtrl.push(AlarmPage);
}
//receive notifications
schedule(a)
{
console.log("receive Notification")
var val=a;
var t:any=a.MSG;
var time:any=a.SEND_TIME;
LocalNotifications.schedule({
title: "Smart Premises",
text: t,
at: time,
sound:this.playSelectedTrack(),
});
}
playSelectedTrack():any{
console.log("audio play");
this.audio.play();
}
Backroundnotifications()
{
//Get Current UserID
var roleid1=localStorage.getItem('Roleid');
this.authservice.getcurrentuserID().subscribe(
data=>{
console.log(data);
this.ApartID=data[0].APART_ID;
this.USERID=data[0].USER_ID;
if(roleid1 === '2' || roleid1 === '5')
{
this.authservice.GetEmergencytype(this.ApartID).subscribe(d=>{
var EM=d;
this.EMERGENCY=EM.filter(a=>a.FROM.toString() != this.USERID.toString());
console.log("this.EMERGENCY");
console.log(this.EMERGENCY);
if(this.EMERGENCY[0].STATUS == 'ON')
{
console.log("this");
console.log(this.EMERGENCY[0]);
}
})
}
})
}
}
这是我的提供者
import { Injectable } from '@angular/core';
import 'rxjs/add/operator/map';
import { AngularFire,FirebaseAuth,FirebaseRef} from 'angularfire2';
import 'rxjs/add/operator/take';
import * as querybase from 'querybase';
import * as firebase from 'firebase';
import { Network } from 'ionic-native';
import { Platform } from 'ionic-angular';
declare var Connection;
@Injectable()
export class Authservice {
users=[];
complaints=[];
neighbours=[];
constructor(public af:AngularFire,public auth:FirebaseAuth) {
console.log('Hello Authservice Provider');
}
//getcurrentuser
getcurrentuser()
{
return this.auth.subscribe(data=>{
//console.log(data);
});
}
//get all user
getalluser()
{
return this.af.database.list('/users',{preserveSnapshot:true});
}
//currentUserID
getcurrentuserID()
{
var email=localStorage.getItem('email');
return this.af.database.list('/users',{query: {
orderByChild: 'EMAIL',
equalTo: email,
}});
}
//Get Emergency
GetEmergencytype(id)
{
var val1=id.toString();
return this.af.database.list('/alarm',{query: {
orderByChild: 'APART_ID',
equalTo: val1
}});
}
}
我在构造函数中调用了这个函数。它在第一次正常工作。点击page1后再转到第2页。这个函数多次被调用。
我的意思是多次安慰这个。很多次。
任何其他用户推送firebase集合。我只需要获取更新值。
我怎么能做到这一点。
请帮助我,
由于