ionic集成websocket

这里使用ng ws工具,

1.安装依赖库

npm install ws --save

2.安装类型定义文件

npm install @types/ws --save

3.编写服务

创建一个websocket.service.ts包,内容如下:

import { Injectable } from '@angular/core';

import { Observable } from "rxjs/Observable";

@Injectable()

export class WebsocketService {

ws: WebSocket = null; //定义websocket对象

constructor() { }

//创建websocket

createObservableSocket(url: string): Observable<any> {

console.log(url);

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.在路由中引用

①、找到你需要引用的模块的路由 xx.module.ts;

②、在头部导入 import { WebsocketService } from './websocket.service';

③、在@NgModule的providers里添加WebsocketService,如图:

5.在控制器中使用

import { WebsocketService } from './websocket.service';

@Component({

templateUrl: 'app.html'

})

export class MyApp {

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);

}

}

 

发布了15 篇原创文章 · 获赞 4 · 访问量 1万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 像素格子 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览