import { Message } from '../models/message' ; import { Injectable } from '@angular/core' ; import { Subject , ReplaySubject } from 'rxjs' ; import { map } from 'rxjs/operators' ; const initialMessages = [ ] ; type IMessagesOperation = ( messages : Message [ ] ) => Message [ ] ; @ Injectable ( ) export class MessagesService { private messagesList : Message [ ] = [ ] ; public newMessages : Subject < Message > = new Subject < Message > ( ) ; public messages : ReplaySubject < Message [ ] > = new ReplaySubject < Message [ ] > ( 1 ) ; public updates : Subject < any > = new Subject < any > ( ) ; public create : Subject < Message > = new Subject < Message > ( ) ; constructor ( ) { this . updates . subscribe ( ( ope ) => { this . messagesList = ope ( this . messagesList ) ; console . log ( this . messagesList ) ; this . messages . next ( this . messagesList ) ; } ) ; this . newMessages . pipe ( map ( function ( message ) : IMessagesOperation { return ( messages ) => { return messages . concat ( message ) ; } ; } ) ) . subscribe ( this . updates ) ; } public addMessage ( message ) { this . newMessages . next ( message ) ; } }