Search code examples
angulartypescriptobservablebehaviorsubject

Typescript: filter BehaviourSubjet asObservable


I'm pretty new to angular and I'm wondering what I'm missing in this situation:

In a service I create a BehaviorSubject to store Websocket events:

@Injectable()
export class GlobalEvent {
  private _events: BehaviorSubject<IWSEvent[]> = new BehaviorSubject([]);
  private socket;
  constructor() {
    this.socket = io(AppConfig.websocketClient);
    this.socket.on('event', (data: IWSEvent) => {
      const collection = this._events.value;
      collection.push(data.msg.object);
      this._events.next(collection);
    });
  }

  list() {
    return this._events.asObservable();
  }

}

Then in another service I'm subscribing to the Observable I'm returning:

@Injectable()
export class InstanceStore {
  constructor(private instanceService: InstanceService, private globalEvent: GlobalEvent) {
    this.globalEvent.list()
      .filter((e) => {
        return e.model === 'Instance';
      })
      .subscribe(
        (data: IWSEvent[]) => {
          const event = data[data.length - 1];
          console.log(event, data);
        }
      );
  }
}

But I'm getting the error: Property 'model' does not exist on type 'IWSEvent[]'. in the filter function while I was expecting to find a single IWSEvent as parameter of the filter function, not the array.

What I'm not understanding?

Thanks


Solution

  • It looks like you have a type mismatch. You have a BehaviorSubject<IWSEvent[]> which will send an instance of IWSEvent[] for each next() call but your filter seems to be written for a single instance of IWSEvent.

    From what it looks like you don't really want to store your events in an array but just have a stream of BehaviorSubject<IWSEvent> then your filter will work as intended and you don't need to grab the last item of the array in your subscribe method.