angular中使用Socket.io實例代碼
更新時間:2017年06月03日 10:45:02 作者:lieefu
本篇文章主要介紹了angular中使用Socket.io實例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
服務(wù)端(nodeJs/express):
let app = require('express')();
let http = require('http').Server(app);
let io = require('socket.io')(http);
io.on('connection', (socket) => {
console.log('user connected');
socket.on('disconnect', function(){
console.log('user disconnected');
});
socket.on('add-message', (message) => {
io.emit('message', {type:'new-message', text: message});
});
});
http.listen(5000, () => {
console.log('started on port 5000');
});
客戶端,創(chuàng)建一個ChatService
import { Subject } from 'rxjs/Subject';
import { Observable } from 'rxjs/Observable';
import * as io from 'socket.io-client';
export class ChatService {
private url = 'http://localhost:5000';
private socket;
sendMessage(message){
this.socket.emit('add-message', message);
}
getMessages() {
let observable = new Observable(observer => {
this.socket = io(this.url);
this.socket.on('message', (data) => {
observer.next(data);
});
return () => {
this.socket.disconnect();
};
})
return observable;
}
}
ChatComponent
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Control } from '@angular/common';
import { ChatService } from './chat.service';
@Component({
moduleId: module.id,
selector: 'chat',
template: `<div *ngFor="let message of messages">
{{message.text}}
</div>
<input [(ngModel)]="message" /><button (click)="sendMessage()">Send</button>`,
providers: [ChatService]
})
export class ChatComponent implements OnInit, OnDestroy {
messages = [];
connection;
message;
constructor(private chatService:ChatService) {}
sendMessage(){
this.chatService.sendMessage(this.message);
this.message = '';
}
ngOnInit() {
this.connection = this.chatService.getMessages().subscribe(message => {
this.messages.push(message);
})
}
ngOnDestroy() {
this.connection.unsubscribe();
}
}
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
AngularJS 獲取ng-repeat動態(tài)生成的ng-model值實例詳解
這篇文章主要介紹了AngularJS 獲取ng-repeat動態(tài)生成的ng-model值實例詳解的相關(guān)資料,這里提供實例代碼及實現(xiàn)效果圖,需要的朋友可以參考下2016-11-11
Angular.js中上傳指令ng-upload的基本使用教程
這篇文章主要給大家介紹了關(guān)于Angular.js中上傳指令ng-upload的基本使用方法,文中通過示例代碼介紹的非常詳細,對大家具有一定的參考學習價值,需要的朋友們下面跟著小編來一起學習學習吧。2017-07-07
Angular-Ui-Router+ocLazyLoad動態(tài)加載腳本示例
本篇文章主要介紹了Angular-Ui-Router+ocLazyLoad動態(tài)加載腳本示例,可以提高加載速度,使用戶體驗更好,有興趣的可以了解一下。2017-03-03
AngularJS iframe跨域打開內(nèi)容時報錯誤的解決辦法
這篇文章主要介紹了AngularJS iframe跨域打開內(nèi)容時報錯誤的解決辦法,需要的朋友可以參考下2015-01-01

