firebase database for chat application like whatsapp with ionic - firebase

i would like to create chat application like whatsapp,
i tried many samples but still now i didn't get full picture how to implement this, because how we can design the database everyone is giving sample json structure but how we can use that json in ionic application ?? or we have to use functions ??
can any one help me the full database and how we can use that in ionic app ?
https://web.chat21.org/
i am planing to implement chat application like this
here is the one to one chat simple code, but i want recent chats list, users list etc.
import { NavController } from 'ionic-angular';
import * as firebase from 'firebase';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
public name = 'surendra';
messagesList = [];
ref = firebase.database().ref('chatrooms/');
newmessage: string;
constructor(public navCtrl: NavController,
) {
this.ref.on('value', data => {
let tmp = [];
data.forEach(data => {
tmp.push({
key: data.key,
name: data.val().name,
message: data.val().message
})
});
this.messagesList = tmp;
});
}
send() {
this.ref.push({
name: this.name,
message: this.newmessage
});
}
}

Related

vuex not loading module decorated with vuex-module-decorators

I get this error when trying to load a store module with the vuex-module-decorators into the initialiser:
vuex.esm.js?2f62:261 Uncaught TypeError: Cannot read property
'getters' of undefined at eval (vuex.esm.js?2f62:261) at Array.forEach
() at assertRawModule (vuex.esm.js?2f62:260) at
ModuleCollection.register (vuex.esm.js?2f62:186) at eval
(vuex.esm.js?2f62:200) at eval (vuex.esm.js?2f62:75) at Array.forEach
() at forEachValue (vuex.esm.js?2f62:75) at ModuleCollection.register
(vuex.esm.js?2f62:199) at new ModuleCollection (vuex.esm.js?2f62:160)
The index.ts file is quite simple and all works until i introduce the modules to the initialiser:
import Vue from 'vue';
import Vuex from 'vuex';
import { AuthenticationModule, IAuthenticationState } from './modules/authentication';
import VuexPersistence from 'vuex-persist';
Vue.use(Vuex);
export interface IRootState {
authentication: IAuthenticationState;
}
const vuexLocal = new VuexPersistence({
storage: window.localStorage,
});
const store = new Vuex.Store<IRootState>({
modules: {
authentication: AuthenticationModule, // if this is not here it works but this will mean the vuex-persist will not work
},
plugins: [vuexLocal.plugin],
});
export default store;
Here is the authentication module i believe is throwing the error:
import { Action, getModule, Module, Mutation, VuexModule } from 'vuex-module-decorators';
import { Generic422, LoginEmailPost, RegisterPost, TokenRenewPost, User, UserEmailPut, UserPasswordPut, UserPut } from '#/api/ms-authentication/model/models';
import { Api } from '#/services/ApiHelper';
import Auth from '#/services/Auth';
import store from '#/store';
export interface IAuthenticationState {
user: User;
authenticated: boolean;
prompt: {
login: boolean,
};
errorRegister: Generic422;
errorLogin: Generic422;
}
const moduleName = 'authentication';
#Module({dynamic: true, store, name: moduleName})
class Authentication extends VuexModule implements IAuthenticationState
{
public authenticated: boolean = false;
public errorRegister: Generic422 = {};
public errorLogin: Generic422 = {};
public prompt = {
login: false,
};
public user: User = {
email: '',
firstName: '',
lastName: '',
birthday: '',
verified: false,
};
#Action({commit: 'SET_USER'})
public async login(data: LoginEmailPost) {
try {
const resp = await Api.authenticationApi.v1LoginEmailPost(data);
Auth.injectAccessJWT(resp.data.tokenAccess.value);
Auth.injectRenewalJWT(resp.data.tokenRenewal.value);
return resp.data.user;
} catch (e) {
return e.statusCode;
}
}
#Mutation
public SET_USER(user: User) {
this.authenticated = true;
this.user = {...this.user, ...user};
}
}
export const AuthenticationModule = getModule(Authentication);
I took this setup from: https://github.com/calvin008/vue3-admin
I don't know if this is a bug or if this is a setup issue but completely stuck here as I intend to use the vuex-persist here to "rehydrate" the store after page reload.
Another completely different way of declaring the stores with this lib was here: https://github.com/eladcandroid/typescript-vuex-example/blob/master/src/components/Profile.vue but the syntax seems it would get wildly verbose when in the vue3-admin it is alll neatly in the store opposed to the component.
Currently I have all the state nicely persisted to local storage but I have no idea due to this error or and lack of exmaple how rehydrate the store with this stored data :/
It seems there are two ways to use the decorators but both are quite different. I like the method i have found from the vie admin as the components are nice and clean, but i cannot inject the modules as https://www.npmjs.com/package/vuex-persist#detailed states should be done :/
I found the answer to be the example vue admin app was not structured quite correctly.
Instead to export the class from the module:
#Module({ name: 'authentication' })
export default class Authentication extends VuexModule implements IAuthenticationState {
Then inject the class as a module into the index and export the module via the decorator but also inject the store into the said decorator:
import Vue from 'vue';
import Vuex from 'vuex';
import Authentication from './modules/authentication';
import VuexPersistence from 'vuex-persist';
import { getModule } from 'vuex-module-decorators';
Vue.use(Vuex);
const vuexLocal = new VuexPersistence({
storage: window.localStorage,
});
const store = new Vuex.Store({
modules: {
authentication: Authentication,
},
plugins: [vuexLocal.plugin],
});
export default store;
export const AuthenticationModule = getModule(Authentication, store);
The result is it all works.

What's the difference between the 'firebase' module, and the "Firebase" one from Ionic Native, in Ionic

Currently found this question (which also puzzled me), but I'm currently using "firebase" to authenticate, and "Firebase" from Ionic Native to get analytics data on the Firebase console. I think that one of these is redundant (since I have the Firebase initialization data once as an object in code, and another one in google-services.json).
So what is the difference, are these two packages substitutes for each other, or is there something else.
u talk about node-modules in ionic. im using if i understand to using it. and my experience tell me its not substitutes for each other. Lets talk about the modules.
First if using:
import firebase from 'firebase'
or
import * as firebase from "firebase";
working with dataSnapshot, snapshot, snap.
if i need object to array data from firebase example:
import firebase from 'firebase';
this.addProduct = firebase.database().ref('/product-List');
this.addProduct.on('value', snapshot => {
this.productList = [];
snapshot.forEach( snap => {
this.productList.push({
category: snap.val().category,
id: snap.key,
in_stock: snap.val().in_stock,
name: snap.val().name,
downloadURL: snap.val().downloadURL,
short_description: snap.val().short_description,
description: snap.val().description,
regular_price: snap.val().regular_price,
sale_price: snap.val().sale_price,
brand: snap.val().brand,
vendor: snap.val().vendor
});
});
});
}
another node-modules ionic-native/firebase
import {Firebase} from '#ionic-native/firebase';
plugin for push notifications, event tracking, crash reporting, analytics and more.
in my case. im using for login with phone and verifyPhoneNumber example:
import {Firebase} from '#ionic-native/firebase';
constructor(private firebasePlugin: Firebase) {
}
Private registerPhone(): void {
if (!this.phoneNumber.value) {
alert('Mohon isi nomor telepon anda');
return;
}
const appVerifier = this.recaptchaVerifier;
const phoneNo = '+62' + this.phoneNumber.value;
if (this.platform.is('cordova')) {
try {
this.firebasePlugin.verifyPhoneNumber(phoneNo, 60).then (credential=> {
// alert("SMS Kode Verifikasi Berhasil dikirim ke Nomor Telp anda");
console.log(credential);
this.showPrompt(credential.verificationId);
}).catch (error => {
console.error(error);
});
}catch(error){alert(error.message)}
}
}

FCMPlugin is not Defined in home.ts

I am trying to send a Push notification Using Firebase and Ionic 3. I have already imported the FCMPlugin in my project though my cmd. When I am creating a new message in firebase and try tos end, I don't receive anything, I run console log in my project and it gives me the following error "FCMPlugin is not defined".
I have declared the Plugin in my home.ts, but I am still getting this error, my home.ts is as follows:
import { Component } from '#angular/core';
import { Platform } from 'ionic-angular';
import {AlertController} from 'ionic-angular';
declare var FCMPlugin: any; // <---- this is the magic line
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
constructor(private alert:AlertController, private platform:Platform) {
this.onNotification();
}
async onNotification(){
try {
await this.platform.ready();
FCMPlugin.onNotification((data)=>{
this.alert.create({
message: data.message
}).present();
},(error) => console.error(error));
}
catch (e) {
console.error(e);
}
}
}
Can anyone provide me some guidance asIi am quite new to ionic?
Thanks in Regards
try using the FCM onNotification method inside an if block so that whenever you use it on a browser or whenever FCM is called before its initialisation it will not throw an error:
if (typeof FCMPlugin != 'undefined') {
FCMPlugin.onNotification((data)=>{})
}

ionic 2 Offline Data Sync using Azure Mobile Apps throws TypeError:Cannot read property 'openDatabase' of undefined

I have created ionic 2 app using visual studio template and trying to develop Offline Data Sync in Azure Mobile Apps functionality.
I have installed node "module of azure-mobile-apps-client" and
using as import * as WindowsAzure from 'azure-mobile-apps-client'; in app.components.ts and initializing store using
Client = new WindowsAzure.MobileServiceClient("url"); but error showing me as "TypeError:Cannot read property 'openDatabase' of undefined".
I have also installed #ionic-native/sqlite node module and cordova-sqlite-storage plugin.
Please see below code:
import { Component } from '#angular/core';
import { Platform } from 'ionic-angular';
import { NavController } from 'ionic-angular';
//declare var WindowsAzure: any;
import * as WindowsAzure from 'azure-mobile-apps-client';
var mobileAppClient, // Connection to the Azure Mobile App backend
store, // Sqlite store to use for offline data sync
syncContext, // Offline data sync context
tableName
var useOfflineSync: boolean = true;
#Component({
selector: 'page-about',
templateUrl: 'about.html'
})
export class AboutPage {
constructor(public navCtrl: NavController, public platform:Platform) {
platform.ready().then(() => {
mobileAppClient = new WindowsAzure.MobileServiceClient("https://myapp.azurewebsites.net");
// Create the sqlite store
store = new WindowsAzure.MobileServiceSqliteStore('store.db');
store.defineTable({
name: 'todoitem',
columnDefinitions: {
id: 'string',
text: 'string',
complete: 'boolean',
version: 'string'
}
});
// Get the sync context from the client
syncContext = mobileAppClient.getSyncContext();
// Initialize the sync context with the store\
syncContext.initialize(store).then((syc) => {
// Get the local table reference.
tableName = mobileAppClient.getSyncTable('todoitem');
// Sync local store to Azure table when app loads, or when login complete.
syncContext.push().then((res) => {
// Push completed
// Pull items from the Azure table after syncing to Azure.
syncContext.pull(new WindowsAzure.Query('todoitem')).then((data) => {
alert(JSON.stringify(data));
}, (err) => {
alert(err);
});
});
}, function (err) {
alert(err);
});
});
}
}
This is probably your client database table columns doesn't match your remote database. Note that removing a column via migration doesn't remove the column in SQLite.

How can i pass Data into my SQLite-Database

Hello there :) I am pretty new to programming and I recently started an IONIC App. However I got stuck. I want to do something like a phone book where you can get random JSON contacts and save them to your sqlite database.
I got this:
import { Storage ] from '#ionic/storage';
#component({
selector: 'page-home'
templateUrl: 'home.html'
});
export class HomePage {
posts: any;
persons: any;
constructor(public navCtrl: NavController, public http: Http, public storage: Storage) {
this.http.get('https://jsonplaceholder.typicode.com/users').map(res=> res.json()).subscribe(data => {
this.posts = data;
});
}
//here i would like to recieve the data from the tapped Item
setData(){
console.log();
this.storage.set('myData', this.posts);
console.log(this.posts);
};
getData(){
this.storage.get('myData').then((data) => {
if (data !=null){
console.log(data);
}
})
};
}
Here is the View:
When i click / tap the save-button i would like to store the values in my sqlite-database and display them in my "local contacts".
<ion-content>
<ion-list>
<ion-item *ngFor="let post of posts">
<ion-list>
<ul><h1>{{post.name}}</h1></ul>
<ul><p>{{post.username}}, {{post.email}}</p></ul>
<ul><p>phone: {{post.phone}}</p></ul>
<button ion-button (click)="setData()">Set Data</button>
</ion-list>
</ion-item>
</ion-list>
</ion-content>
Maybe someone faced similar problems and can help me with this.
Thanks :)
The best way to handle persistent storage with Ionic is using ionic-storage.
Ionic Storage is a package created and maintained by the ionic team to abstract development from the specifics of each browser or platform and automatically use the best storage solution available.
1. Installing Dependencies
In your case for SQLite you need to first install the dependencies for both Angular and Cordova:
npm install #ionic/storage --save
and
cordova plugin add cordova-sqlite-storage --save
Then edit your NgModule declaration in src/app/app.module.ts to add IonicStorageModule as an import:
import { IonicStorageModule } from '#ionic/storage';
#NgModule({
declarations: [...],
imports: [
IonicModule.forRoot(MyApp),
IonicStorageModule.forRoot({
name: '__mydb',
driverOrder: ['indexeddb', 'sqlite', 'websql'],
})
],
bootstrap: [...],
entryComponents: [...],
providers: [...],
})
export class AppModule { }
2. Inject Storage into your component
import { Component } from '#angular/core';
import { Storage } from '#ionic/storage';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
constructor(public storage: Storage) {}
}
3. Storing data in SQLite
Whenever you access storage, make sure to always wrap your code in the following:
storage.ready().then(() => { /* code here safely */});
3.1 Saving a key-value pair
storage.ready().then(() => {
storage.set('some key', 'some value');
});
3.2 Retrieving a value
storage.ready().then(() => {
storage.get('age').then((val: string) => {
console.log('Your age is', val);
});
});
3.3 Deleting a key-value pair
storage.ready().then(() => {
storage.remove('key').then((key: string) => { /* do something after deletion */})
});

Resources