Angular2 Observable - How to call next from outside of the Observable's constructor

You should create a Subject for that

this.myObservable$ = new Subject();

And then you can call at any point:

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

Or use subscribe:

this.myObservable$.subscribe(...)

Actually Subject is used for both publisher and subscriber, and here I think you need only to publish your value, so simply use Observable.

By using observable, assign Subscriber to class level variable and then use it, like below code

subscriber: Subscriber<boolean>;

public observe(): Observable<boolean> {

    return new Observable<boolean>(subs => {
      this.subscriber = subs;
    });
  }

public callNext() {

    if (this.subscriber) {
      this.subscriber.next();
      this.subscriber.complete();
    }
  }

Two ways:

  1. Make myObservable$ public:

    public myObservable$: Observable;
    
  2. Encapsulate the observable in a subject stream, and provide a helper to call next:

    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);  
      }
    }
    

Tags:

Angular

Rxjs