[英]error TS2339: Property '_ws' does not exist on type 'void'
I've recently started with Angular2. 我最近开始使用Angular2。 After reading this article I wanted to play around with websockets and reactive extensions.
阅读本文后,我想尝试一下websockets和响应式扩展。 I used the websocket class from the article which compiled fine.
我使用了编译良好的文章中的websocket类。 The I wanted to call it from the ngOnInit method.
我想从ngOnInit方法中调用它。 I'm not entirely sure how to do this.
我不太确定该怎么做。 So I created a new stance of the class and then initalised the wrapper method, but it didn't work.
因此,我创建了该类的新姿态,然后启动了wrapper方法,但这种方法无效。 I'm just a little unsure of the syntax to init the method.
我只是不确定初始化该方法的语法。
Thanks for the help. 谢谢您的帮助。
let message = 'test';
let ws = new WebSocketService();
let sock = ws.initializeWebSocket('www.google.com');
sock._ws.send();
sock._ws.close();
import { Injectable } from '@angular/core';
import {Observable} from 'rxjs/Observable';
import 'rxjs/Rx';
@Injectable()
export class WebSocketService {
private _wsObservable;
private _ws;
private _url ='www.google.com';
initializeWebSocket(_url) {
this._wsObservable = Observable.create((observer) => {
console.log('this._wsObservable');
this._ws = new WebSocket(_url);
this._ws.onopen = (e) => {
console.log('onopen');
};
this._ws.onclose = (e) => {
console.log('onclose');
if (e.wasClean) {
observer.complete();
} else {
observer.error(e);
}
};
this._ws.onerror = (e) => {
console.log('onopen');
observer.error(e);
};
this._ws.onmessage = (e) => {
console.log("this._wsObservable");
observer.next(JSON.parse(e.data));
};
return () => {
this._ws.close();
};
}).share();
}
}
Try the following 尝试以下
@Injectable()
export class WebSocketService {
private _wsObservable;
private _ws;
private self = this;
private _url ='www.google.com';
initializeWebSocket(_url) {
and replace instances of this
with self
- you are getting this error as the annon function Observable.create
is not bind this
to the caller 和替换的情况下,
this
与self
-你得到这个错误的annon功能Observable.create
不绑定this
给调用者
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.