Answer the question
In order to leave comments, you need to log in
How to transfer data from the service to the controller in real time?
I would like to implement a chat following the example only with the division of functionality in Angular.
HTML
<form name="publish" ng-submit="msgSend()">
<input type="text" name="message">
<input type="submit" value="Send">
</form>
<p >{{collection}}</p>
function chatController($scope, chatService) {
// on submit call method from service
$scope.msgSend = function() {
var msg = document.forms.publish.message.value;
chatService.send(msg);
}
// get message
$scope.collection = chatService.get;
}
function chatService() {
// open websocket connection
var socket = io.connect('http://localhost:8080');
// send msg to server
function msgSend(msg) {
socket.emit('message', msg);
};
function msgGet(msg) {
return msg;
};
// catch messages from server in realtime
var tmp;
socket.on('message', function(msg) {
tmp = msg;
});
// something like interface
var methods = {
send: msgSend,
get: tmp
};
return methods;
}
io.on('connection', function(socket){
//once server get message
socket.on('message', function(msg){
var collection = [];
collection.push(msg);
//send collection array to all users
io.emit('message', collection);
});
});
Answer the question
In order to leave comments, you need to log in
class ChatComponent {
constructor(messages) {
this.messages = messages;
this.list = [];
}
$onInit() {
this.messages.list().then(
(list) => this.list = list;
);
this.messages.onNewMessage((message) => {
this.list.push(message);
});
}
}
angular
.module('app')
.component('messageList', {
controller: ChatComponent,
templateUrl: 'chat/messages.html'
}
class MessagesListComponent {
}
module.component('messageList', {
bindings: {
messages: '='
},
controller: MessagesListComponent
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question