-1

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?

  • You can still use promises in Angular. If you want to convert an existing promise to an observable, see e.g. https://stackoverflow.com/q/39319279/3001761. Or if you want to convert the whole thing to an observable, you probably want to look in [subjects](https://rxjs.dev/guide/subject). – jonrsharpe Jul 29 '22 at 08:21

1 Answers1

0

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();
}
Random
  • 3,158
  • 1
  • 15
  • 25