我最近刚开始使用Angular2。阅读this article后,我想玩网页框和反应式扩展。我使用了编译好的文章中的websocket类。我想从ngOnInit方法调用它。我不完全确定如何做到这一点。所以我创建了一个新的类的立场,然后启动了包装方法,但它没有工作。我只是不太确定初始化方法的语法。
感谢您的帮助。
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();
}
}
答案 0 :(得分:1)
尝试以下
@Injectable()
export class WebSocketService {
private _wsObservable;
private _ws;
private self = this;
private _url ='www.google.com';
initializeWebSocket(_url) {
并将this
的实例替换为self
- 您收到此错误,因为annon函数Observable.create
未绑定this
给调用者