ng websocket
ng使用websocket
1.安装依赖库
npm install ws --save
2.安装类型定义文件
npm install @types/ws --save
3.编写服务
import { Injectable } from '@angular/core';
import {Observable} from "rxjs/Observable";
@Injectable()
export class WebSocketService {
ws:WebSocket;
constructor() { }
createObservableSocket(url:string):Observable<any>{
this.ws=new WebSocket(url);
return new Observable(
observer=>{
this.ws.onmessage=(event)=>observer.next(event.data);
this.ws.onerror=(event)=>observer.error(event);
this.ws.onclose=(event)=>observer.complete();
}
)
}
sendMessage(msg:string){
this.ws.send(msg);
}
}
4.在控制器中使用
import { Component, OnInit } from '@angular/core';
import {Observable} from "rxjs/Observable";
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/throttleTime';
import 'rxjs/add/observable/fromEvent';
import 'rxjs/add/operator/retry';
import {observable} from "rxjs/symbol/observable";
import {HttpService} from "../service/http.service";
import {WebSocketService} from "../service/web-socket.service";
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
constructor(private httpreq:HttpService,private wsService:WebSocketService) {
}
ngOnInit() {
//this.httpreq._get('',(data)=>console.log(data));
this.wsService.createObservableSocket('ws://localhost:8080')
.subscribe(
data=>console.log(data),
err=>console.log(err),
()=>console.log('it s over')
)
}
sendMessageToServer(msg:string){
this.wsService.sendMessage(msg);
}
}