Angular2 Observable - how to call the next Observable constructor from outside

I am creating a service that provides an Observable. In this service, I receive external function calls that should call the next Observable call so that different users receive a subscription event. In the Observer constructor, I can call further, and everything works fine, but how can I access this outside the constructor so that external triggers can trigger the following calls?

private myObservable$: Observable<any>; 

During service initialization

 this.myObservable$ = new Observable(observer => { observer.next("initial message"); } 

Then, in other methods of the same service, I want to be able to execute something like

 this.myObservable$.observer.next("next message"); 

Above obviously does not work, but how can I achieve this?

I assume that I am missing something basic, as there should be a way to generate additional messages outside the original Observable constructor

+7
angular rxjs
source share
2 answers

You must create a Subject for this

 this.myObservable$ = new Subject(); 

And then you can call at any time:

 this.myObservable$.next(...); 

Or use a subscription:

 this.myObservable$.subscribe(...) 
+9
source share

Two ways:

  • Make myObservable $ public:

     public myObservable$: Observable; 
  • Encapsulate what is observed in the subject stream and provide the assistant with the following call:

     export class TestService { public myObservable$: Observable; private _myObservableSubject: Subject; constructor() { this._myObservableSubject = new Subject(); this.myObservable$ = this._myObservableSubject.asObservable(); } public NextMessage(message?: string): void { this._myObservableSubject.next(message); } } 
+2
source share

All Articles