Home > front end >  How to resolve observable in Angular the same way as deferred
How to resolve observable in Angular the same way as deferred

Time:07-30

I'm currently switching from AngularJS to Angular and finding trouble moving from promises to observables. Here excerpt from my code in AngularJS.

var deferred = $q.defer(),
    frame = document.createElement('newFrame');

/// some code here...

frame.onload = function () {
    /// code..
    deferred.resolve();
}

frame.onerror = function () {
    /// code..
    deferred.reject();
}

document.body.appendChild(frame);

return deferred.promise;

I could not find how to rewrite this code in Angular using observables. Looking through questions on StackOverflow I found this question, but here I don't use HTTP API, so it is harder to convert.

Is there any way around it?

CodePudding user response:

You can always use subjects (which are special observables)

// caller
this.myObservableFunc().subscribe({
  next: () => {
    // code when success
  },
  error: () => {
    // code when error
  }
);

// function
public myObservableFunc(): Observable<void> {
  var subject$: Subject<void> = new Subject(),
      frame = document.createElement('newFrame');

  /// some code here...

  frame.onload = function () {
    /// code..
    subject$.next(); // trigger success
    subject$.complete(); // this subject will not be triggered anymore
  }

  frame.onerror = function () {
    /// code..
    subject$.error(); // trigger error (which also ends the subject)
  }

  document.body.appendChild(frame);

  return subject$.asObservable();
}
  • Related