Ways to address observables in Angular in a manner similar to deferred objects

Transitioning from AngularJS to Angular has posed a challenge for me, especially when it comes to moving from promises to observables. Below is an example of 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 have been struggling to rewrite this code using observables in Angular. After browsing through various questions on StackOverflow, I came across this question. However, since I am not using HTTP API in this scenario, the conversion process seems more complex.

Is there any alternative solution available?

Answer №1

Utilize subjects, special observables, to handle asynchronous operations.

// Example of usage
this.myObservableFunc().subscribe({
  next: () => {
    // Code to execute on success
  },
  error: () => {
    // Code to execute on error
  }
);

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

  /// Some code here...

  frame.onload = function () {
    /// Execute this code on load...
    subject$.next(); // Trigger success
    subject$.complete(); // This subject will not emit values anymore
  }

  frame.onerror = function () {
    /// Execute this code on error...
    subject$.error(); // Trigger error (also completes the subject)
  }

  document.body.appendChild(frame);

  return subject$.asObservable();
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubleshooting Angular 2 with TypeScript: Issue with view not refreshing after variable is updated in response handler

I encountered a problem in my Angular 2 project using TypeScript that I could use some help with. I am making a request to an API and receiving a token successfully. In my response handler, I am checking for errors and displaying them to the user. Oddly en ...

ng-class not functioning properly when invoked

In my controller, I have the following function: $scope.menus = {}; $http.get('web/core/components/home/nav.json').success(function (data) { $scope.menus = data; $scope.validaMenu(); }).error(function () { console.log('ERRO') }); ...

Encountering an Issue Executing Selenium Test on jQuery v2.0.2 and Play Framework

While I may not be a selenium expert, it seems that I've stumbled upon a bug when trying to utilize jQuery v2.0.2 with my Play Framework 2.2.1 application instead of the default jQuery v.1.9.0. Whenever I run "play test", I encounter the following err ...

What is the process of adding information to a JSON file?

I'm looking to store my data in an external JSON file and have it update the list when the page is reloaded. Can anyone assist with this? Below is my code: $scope.addUser = function() { var user = { id: null, login: '', ...

Mastering Array Dispatch in VueJS

I've encountered an issue while trying to send an array of data to the backend. I attempted to include [] in the dispatch variables and on the backend, but it only captures the last data sent to the backend. My objective is to associate each data with ...

Strategies for Creating a Test Suite for RepositoryFactory in Vue.js/Nuxt.js

Summary of RepositoryFactory Implementation An implementation of the RepositoryFactory pattern has been carried out for API connection in a Vue.js/Nuxt.js application. For more details, refer to this article: here hogeRepository.ts import { NuxtAxiosInst ...

The GIF Loader fails to animate while an AJAX request is in progress

Displaying a DIV element containing a loading GIF image while waiting for an AJAX call response. Initially, the DIV element is hidden. Upon clicking a checkbox, the loader DIV is shown, followed by the completion of the AJAX call, and then hiding the load ...

The issue of req.file being consistently undefined in Node.js multer

I am having issues trying to upload a file using multer because the req.file is always undefined and the destination folder remains empty: Server: var express = require('express'); var multer = require('multer') var app = express(); ...

Steps for importing a CommonJS module with module.exports in Typescript

When working with ES5 code, I encountered an error that I cannot seem to resolve. Despite following the language spec and checking my TypeScript version 1.7.5, I still can't figure out why this error is occurring. Error TS2349: Cannot invoke an expre ...

Ways to trigger an onClick event of one div based on the presence of another div

I'm looking to execute a function when a specific type of button is clicked on my HTML page. I have approximately 10 buttons on the page and I've written the following code to call a function when a button is clicked: $('.divname').ea ...

Modifying button appearance upon clicking using JavaScript

JavaScript: const buttons = document.getElementsByClassName("togglebtn"); for (let i = 0; i < buttons.length; i++) { buttons[i].onclick = function () { this.classList.toggle("active"); } } html: <md-butt ...

Is it universally compatible to incorporate custom attributes through jquery metadata plugin in all web browsers?

Picture this: a fictional markup that showcases a collection of books with unique attributes, utilizing the metadata plugin from here. <div> Haruki Murakami </div> <div> <ul> <li><span id="book5" data="{year: 2011} ...

Issue with the intersection of mouse and camera rays in three.js

I've been working on a simple program that involves creating a clickable 3D object in Three.js. I've referenced my code from When I click directly on the object, it works as expected, but upon examining the resulting array, I noticed that the ob ...

Implementing Bootstrap 4 validation within a modal using JSON data

I've been struggling to validate the TextBoxFor before submitting the form. Despite trying various methods, I haven't managed to make it function properly. Modal: <div class="modal fade" id="MyModal_C"> <div class="modal-dialog" st ...

I'm having some unexpected reflections with the threejs cube camera

I'm currently experimenting with creating an object that reflects on all sides. Although I've made progress, I seem to be encountering some issues. At certain angles, I can only see partial reflections and the scale of the reflection is much larg ...

Using Gulp Filter in Conjunction with Source Maps

My initial query was similar to this one here, but it led me to delve deeper into research and explore a new approach. Essentially, I am attempting to consolidate all my .js and .coffee files within a single gulp.src() object and execute relevant tasks ba ...

Tips for minimizing the transfer time of large arrays using ajax

https://i.stack.imgur.com/IP0oe.pngDescription I am currently working on transferring a JSON object from the server to the client using PHP and JavaScript via AJAX. The JSON object contains a large array (200x200) of integers. The server is running on lo ...

How to prevent horizontal scrolling on the right side of a div element

Greetings! I am relatively new to coding and currently facing an issue with stopping horizontal scrolling when the second div is fully visible on the screen (while keeping the third div hidden). Here is the code snippet I have been working on: $(docum ...

Incomplete JSON response being received

We set up an express server to call an API and successfully requested the JSON object in our server. However, we are facing an issue where the JSON data is getting cut off when being displayed as a complete object on the client side. We tried using parse i ...

Can a custom type guard be created to check if an array is empty?

There are various methods for creating a type guard to ensure that an array is not empty. An example of this can be found here, which works well when using noUncheckedIndexedAccess: type Indices<L extends number, T extends number[] = []> = T["le ...