Angular - 我不能创建一个类属性?

时间:2018-01-30 08:23:57

标签: javascript angular typescript

我正在学习Angular ..对于搜索我想使用通过websockets发送和接收数据的服务。

我使用angular-cli创建了一项服务:

ng -g-s websocketsService

现在这是我的websockets.service.ts:

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


@Injectable()
export class WebsocketsService {

    private _search: string;
    private url = 'ws://localhost:1337';

    constructor() {
    }

    sendQuery(search) {
        this._search = search;
        console.log('Perform search for: ' + this._search);

        const websocket = new WebSocket(this.url);

        websocket.onopen = () => {
            websocket.send(JSON.stringify({
                data: this._search
            }));
        };

        websocket.onmessage = function (event) {
            console.log(event.data);
        };

        websocket.onerror = function (event) {
            console.log('A Error has occured!');
        };

        websocket.onclose = function (event) {
            console.log('Connection closed');
        };
    }
}

到目前为止一切顺利......这有效......但这对我来说似乎不是最佳实践..我希望将websocket-connection作为类属性,这样我就可以在一个mehtod中建立连接并发送数据在另一种方法中..

但是当我在类private ws;中定义一个变量然后尝试用this.ws来处理它时,我总是会得到一个错误,即this.ws未定义(?)

我在这里做错了什么?我怎么能让这个更漂亮呢?

这是一个简单的尝试,它不起作用,我不明白为什么:

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


@Injectable()
export class WebsocketsService {

  private _search: string;
  private url = 'ws://localhost:1337';

  public wsConnection;

  constructor() {
    this.create();
  }

  create() {
    this.wsConnection = new WebSocket(this.url);
  }

  sendQuery(search) {
    this._search = search;
    console.log('Perform search for: ' + this._search);


    this.wsConnection.onopen = () => {
      this.wsConnection.send(JSON.stringify({
        data: this._search
      }));
    };     

} }

连接已建立,但在sendQuery()方法中,send()不起作用..我在控制台中也没有错误。

2 个答案:

答案 0 :(得分:1)

IMO,你必须先在构造函数中初始化你的websocket(及其事件回调)成员,然后在类方法中使用它。

@Injectable()
export

class WebsocketsService {

  private _search:string;
  private url ='ws://localhost:1337';
  private websocket:WebSocket;

  constructor() {
    this.websocket = new WebSocket(this.url);
    this.websocket.onopen = function() {
      console.log('Connection opened');
    };

    this.websocket.onmessage = function(event) {
      console.log(event.data);
    };

    this.websocket.onerror = function(event) {
      console.log('A Error has occured!');
    };

    this.websocket.onclose = function(event) {
      console.log('Connection closed');
    };
  }

  sendQuery(search) {
    this._search = search;
    console.log('Perform search for: ' + this._search);

    this.websocket.send(JSON.stringify({
      data:this._search
            }));
  }
}

编辑: 对于每个websocket发送方法调用,如果服务器关闭连接,我们之后就不能使用send方法。 我们必须使用onopen处理程序来发送数据。每次调用都会创建自己的websocket,并在连接状态为OPEN时发送数据。

@Injectable()
export

class WebsocketsService {

  private _search:string;
  private url ='ws://localhost:1337';

  constructor() {
  }

  sendQuery(search) {
    this._search = search;
    console.log('Perform search for: ' + this._search);

    let websocket = new WebSocket(this.url);
    websocket.onopen = function() {
      console.log('Connection opened');
      websocket.send(JSON.stringify({
          data:this._search
      }));
    };

    websocket.onmessage = function(event) {
      console.log(event.data);
    };

    websocket.onerror = function(event) {
      console.log('A Error has occured!');
    };

    websocket.onclose = function(event) {
      console.log('Connection closed');
    };   
  }
}

答案 1 :(得分:1)

export class CustomWebSocket {

  websocket: WebSocket;

  constructor(
    private url: string
  ) {
    this.websocket = new WebSocket(url);
  }

  sendQuery(search: string) {
    websocket.onopen = () => websocket.send(JSON.stringify({ data: search }));
    websocket.onmessage = event => console.log(event.data);
    websocket.onerror = event => console.log('A Error has occured!');
    websocket.onclose = event => console.log('Connection closed');
  }
}

在您的服务中:

export class WebsocketsService {
  public sockets: CustomWebSocket[] = [];
  constructor() {}
  createWS(url: string): CustomWebSocket {
    const ws = new CustomWebSocket(url);
    this.sockets.push(ws);
    return ws;
  }
}

在您的组件中:

this.myService.createWS('url').sendQuery('my query');

我相信这是最干净的方式,但这是我的个人观点。

相关问题