【发布时间】:2018-01-21 11:02:09
【问题描述】:
我编写了一个 Angular 服务,它通过 socket.io 连接到我的后端。我在_getStripes() 方法中正确获取了服务器数据,并使用from() 将它们转换为Observable,并使用最近创建的observable 设置类变量_LEDs。
公共方法getStripes()在另一个组件中被调用和订阅,每次都返回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);
}
}
【问题讨论】:
-
这可能是竞争条件吗?我猜想
return是在处理emit之前发生的。就像一个测试,如果你睡在getStripes中的emit和return之间,让其他一切有机会“安顿下来”,会发生什么?
标签: angular typescript socket.io rxjs