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


    }

  • 相关阅读:
    无向图的双连通分量
    以管理员身份运行软件cmd命令
    异或
    递推求解DAG最长路径长度及最长路径条数
    有向图转强连通图最少加边数
    Tarjan强连通分量(scc)
    uni封装request请求
    生命周期
    页面路由,以及传值
    WXS 模块
  • 原文地址:https://www.cnblogs.com/norm/p/8023491.html
Copyright © 2020-2023  润新知