Hi,
I am working on an app that has multiple page and one of them is chat. I use mongodb to store other related data. In the mean time I use socket.io for the chat module. The thing is socket transfers the data without an issue and I am saving all the data into a variable for the time being. I would like to know what is the best way to store the chat data in mobile since I am not going to store this data in the server. Or should I do that?
I am posting the code I have for the reference…
Thanks
Chat-service.ts
import {Injectable, NgZone} from '@angular/core';
import {Http} from '@angular/http';
import 'rxjs/add/operator/map';
import io from 'socket.io-client';
import {Auth} from './auth'
import {Storage} from '@ionic/storage';
/*
Generated class for the ChatService provider.
See https://angular.io/docs/ts/latest/guide/dependency-injection.html
for more info on providers and Angular 2 DI.
*/
@Injectable()
export class ChatService {
public socket: any;
public chats: any;
public userid: any;
constructor(public http: Http, public storage: Storage, public authService: Auth, public zone: NgZone) {
console.log('Hello ChatService Provider');
this.userid = this.authService.getid();
this.chats = [];
this.socket = io(MYSERVER URL, {query: 'thisuser=' + this.userid}); <-- I am passing this data to create an of all the connected users in the server
this.socket.on('chat_message', (data) => {
this.zone.run(() => {
let chatobj = this.chats.find(obj => obj.from == data.from);
let index = this.chats.indexOf(chatobj);
if (chatobj) {
this.chats.fill(chatobj.msgs.push(
{
msg: data.msg,
rcvd: 1
}),
index,
index++
)
}
else if (chatobj == undefined) {
this.chats.push(
{
from: data.from,
msgs: [
{
msg: data.msg,
rcvd: 1
}
]
});
}
});
console.log(this.chats);
});
}
send(obj) {
if (obj.msg.trim() != '') {
this.socket.emit('chat_message', {msg: obj.msg, reciever: obj.to, from: this.authService.thisuser});
this.zone.run(() => {
let chatobj = this.chats.find(objnew => objnew.from == obj.to);
let index = this.chats.indexOf(chatobj);
if (chatobj) {
this.chats.fill(chatobj.msgs.push(
{
msg: obj.msg,
sent: 1
}),
index,
index++
)
}
else if (chatobj == undefined) {
this.chats.push(
{
from: obj.to,
msgs: [
{
msg: obj.msg,
sent: 1
}
]
});
}
});
console.log(this.chats);
}
}
}