我编写了一个与socket.io连接到后端的角度服务。我在_getStripes()
方法中正确获取了服务器数据,并将其from()
转换为Observable并_LEDs
使用最近创建的observable设置了类变量。
getStripes()
在另一个组件中调用并预订public方法,并每次返回undefined
。
led.service.ts:
import {Injectable} from '@angular/core';
import * as io from 'socket.io-client';
import {LED} from './led';
import {Observable} from 'rxjs/Observable';
import {from} from 'rxjs/observable/from';
@Injectable()
export class LedService {
private _io;
private _LEDs: Observable<LED>;
constructor() {
this._io = io('http://localhost:80');
// Subscribe getStripes Event
this._io.on('getStripes', this._getStripes);
// Initial Request Stripes from Server
this._io.emit('getStripes');
}
/**
* Server Response
* @param {LED[]} data
* @private
*/
private _getStripes(data: LED[]) {
console.log('Got Stripes: ', data); // works
this._LEDs = from(data);
}
/**
* Get the current connected LEDStripes
* @returns {Observable<LED>}
*/
public getStripes(): Observable<LED> {
// request latest Stripes
this._io.emit('getStripes');
return this._LEDs; // always undefined
}
public setStripeColor(name: string, color: string) {
this._io.emit('setStripeColor', name, color);
}
}
您需要将订阅与发射分开。
订阅将建立管道以接收传入的数据,但发出发送数据。它看起来像是请求/响应样式,因为事件和发出参数是相同的字符串,但是在任何情况下两者之间都存在时间延迟,因此需要事先建立管道。
尝试将主题用于this._LEDS
。
在服务中
import {Injectable} from '@angular/core';
...
import {Subject} from 'rxjs/Subject';
@Injectable()
export class LedService {
private _io;
private _LEDs = new Subject<LED>();
public LEDs = this._LEDs.asObservable(); // Subscribe to this
constructor() {
...
// Subscribe getStripes Event
this._io.on('getStripes', this._getStripes.bind(this) );
...
}
/**
* Server Response
* @param {LED[]} data
* @private
*/
private _getStripes(data: LED[]) {
data.forEach(led => this._LEDs.next(led));
// OR send the whole array as a single emit if it suits your application better
// this._LEDs.next(data);
// in which case the declaration above would be
// private _LEDs = new Subject<LED[]>();
}
/**
* Get the current connected LEDStripes
* @returns void
*/
public getStripes(): void {
// request latest Stripes
this._io.emit('getStripes');
}
在组件中
ngOnInit() {
// subscribe to the LEDs
this.sub = this.ledService.LEDS.subscribe(leds => {
// do something with data
})
// or use the subscription directly in the template
// with <div> {{ (ledService.LEDS | async) }} </div>
}
getFresh() {
this.ledService.getStripes();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句