从角度通过websocket连接发送数据

时间:2018-07-03 15:18:24

标签: angular websocket rxjs

我在弄清楚如何发送以下的json到websocket连接以从服务器开始数据流时遇到了麻烦。

{"type": 1, "productId":"1234"}

我已经为websocket创建了服务。我正在创建一个可观察对象以将数据流发送到哪里。

import {Subject} from "rxjs/subject";
import { Subscription } from 'rxjs/Subscription';
import { Observable } from 'rxjs/Observable';
import { Observer } from 'rxjs/Observer';
import { Injectable } from '@angular/core';

import 'rxjs/add/observable/dom/webSocket';

@Injectable()
export class WebsocketService {
    private socket: Subject<MessageEvent>;

    constructor() { }

    public connect(url): Subject<MessageEvent> {
        if(!this.socket) {
          this.socket = this.create(url);
        }
        return this.socket;
    }

    private create(url): Subject<MessageEvent> {
        let ws = new WebSocket(url);
        let observable = Observable.create(
            (obs: Observer<MessageEvent>) => {
                ws.onmessage = obs.next.bind(obs);
                ws.onerror = obs.error.bind(obs);
                ws.onclose = obs.complete.bind(obs);
                return ws.close.bind(ws);
            }
        );
        let observer = {
            next: (data: Object) => {
                if (ws.readyState === WebSocket.OPEN) {
                    ws.send(JSON.stringify(data));
                }
            },
        };
        return Subject.create(observer, observable);
    }
}

这是我调用服务的组件

import { Component, OnInit, ViewChild } from '@angular/core';
import { WebsocketService } from '../../services/websocket.service';
import { BaseChartDirective } from 'ng2-charts/ng2-charts';
import homeChartData from '../../../assets/json/home-chart-data';

@Component({
    selector: 'app-home',
    templateUrl: './home.component.html',
    styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {

    constructor(private _socket: WebsocketService) {
        this._socket.connect('ws://localhost:5000/ws').subscribe(({ data }) => {
        const dataDetails = JSON.parse(data);
        const chartDataSet = [
          {
            label: 'Offer',
            lineTension: 0, 
            data: dataDetails.offers
          }
        ]
        const labels = Array.apply(null, {length: dataDetails.offers.length}).map(Number.call, Number);
        this.chartArray = [{data: chartDataSet, labels}];
      })
    }

    ngOnInit() {
    }

}

因此,我有一个问题。

在服务或组件中在哪里执行ws.send(json)?

0 个答案:

没有答案