Home > Software engineering >  Emit from observer after callback returns
Emit from observer after callback returns

Time:03-15

I have a component, called MyComponent. This component has a form with a submit button. In the onSubmit() function for this button, i am calling a myService.postData(). subscribe (...) etc.

The problem is with the service code. The myService postData() method should return an Observable but there is some complication here because the service is using a socket (socket.io) to send data to the server and get an acknowledgement. For this i pass a callback function to socket.emit as mentioned in socket.io documentation. The observable is supposed to return this response (received in the callback ) but here I have a problem because of asynchronous programming, how to return the response in the observable in the callback. I have tried a few things but they don't seem to work. Please find code of the service as follows: export class MyService {

constructor(private socketService: SocketService) { }

postData(newData: any ): Observable {

var myObservable: Observable<any>;

this.socketService.getSocket().emit('post-data', newData,(response:any) => {
//server will return a json object with values:  {status:''} which will be the response
// that is passed to the MyComponent subscribe method

  myObservable = new Observable((observer) => {
    observer.next(response);

    //return myObservable gives error because then not all paths of postData() return a value.
  });

});

return myObservable; //this is undefined when it is received by MyComponent

}

Thanks

CodePudding user response:

have you tried to use the ngx.socket.io events ? Here is the lib : https://www.npmjs.com/package/ngx-socket-io

All you need is to watch some data from the socket object :

this.socket.fromEvent('message')

CodePudding user response:

postData(newData: any ): Observable {
  const subject$ = new ReplaySubject<any>(1); 
  this.socketService.getSocket().emit('post-data', newData,(response:any) => {
    subject$.next(response);
  });

  return subject$.asObservable();
}
  • Related