Opt for Observable over Promise in your applications

I have implemented this function in one of my servlets:

private setValues() {
    this.config.socket.on('config.weather', (values:any) => {
      console.log(values);
}

However, I would like to refactor it to something like this:

private setValues() {
    this.config.load('weather').then((values:any) => {
      console.log(values);
}

This is the new method implementation in the socket Service:

public load(key: string) {
    return new Promise(resolve => {
        this.socket.on('config.' + key, values => resolve(values));
});

Although this solution works for the initial call, subsequent socket triggers do not send data to the setValues() function as Promises only work once.

I believe I need to use an Observable instead, but I am unsure where to integrate it within the code.

Answer №1

By implementing a subject, my issue was resolved:

public load(key: string) {
    let sub = new Subject();
    this.socket.on('config.' + key, values => {
        sub.next(values);
    });
    return sub;
}

Additionally,

private setValues() {
    this.config.load('weather').subscribe((values:any) => {
      console.log(values);
}

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

Utilizing movingMarker from leaflet-moving-marker in Angular: A Step-by-Step Guide

I am currently working on incorporating the leaflet-moving-marker plugin but encountering some errors in the process. import {movingMarker} from 'leaflet-moving-marker' var myMovingMarker = L.movingMarker([[48.8567, 2.3508],[50.45, 30.523 ...

What could be causing the background image on my element to not update?

I'm attempting to utilize a single background image that is 3 pixels wide and 89 pixels tall. Each vertical stripe of 1 pixel will serve as the background for a different div. I had presumed that adjusting the background-position by -1px 0 and specif ...

When directed to a different page, Fetch does not activate

Having trouble getting the fetch function to run more than once in my application. It works the first time, loading the page with received data, but when I navigate to a new URL without refreshing the page, nothing changes - not even the state. The same is ...

Using a React component to import a module for publishing on NPM

Creating my first React component for NPM publication has been quite the learning experience. I decided to use the react-webpack-component package from Yeoman to kickstart my project. However, upon installing and importing my component into a React app, I ...

The function for the "load next page" action in ngInfiniteScroll is continuously triggered

After attempting to implement infinite scrolling using the "loading remote data" example from the ngInfiniteScroll website, I am facing a problem. The function nextPage() is being called continuously until all records have been loaded (controlled by an of ...

Angular Boilerplate is experiencing difficulties in properly reading ABP

Working on my boilerplate project, I am now diving into consuming backend services (using asp .net) in Angular through http requests. However, I encountered an issue when trying to implement the delete method in mycomponent.ts, as TypeScript was not recogn ...

Vue.js isn't triggering the 'created' method as expected

I have a main component called App.vue. Within this component, I have defined the created method in my methods object. However, I am noticing that this method is never being executed. <template> <div id="app"> <Header /> <Ad ...

Obtain a reference to a class using a method decorator

My goal is to implement the following syntax: @Controller('/user') class UserController { @Action('/') get() { } } Now in the definition of decorators: function Controller (options) { return function(target: any) { let id ...

How can I notify an error in CoffeeScript/JavaScript when a parameter is not provided?

Initially, I believed that my code was clever for accomplishing this task: someFunction = (arg1, arg2, arg3) -> if _.some(arguments, (a) -> a is undefined) throw new Error "undefined parameter" My goal was to throw an error if any of the para ...

What is the procedure for inputting the settings for the export module in webpack?

I am currently working on setting up this webpack configuration file. However, I encountered an issue where the error message states that "any" is being used as a value instead of a type. How can I resolve this issue? module.exports:any = { ...

Instructions on setting div opacity when Overflow is set to visibleExplanation on setting opacity for div with Overflow

In my HTML code, I have a div element and an image tag stacked one on top of the other. The div is smaller than the image. I have set the overflow property to visible for the div. My query is, when I add an image to the image tag, the content that overflow ...

Trouble arises when accessing GET form in php/Ajax

I am in the process of creating a dynamic website. At the top, I have an input form that, when submitted, should display the output from an asynchronous request to a PHP page using echo to show what was submitted. Unfortunately, it's not functioning ...

Exporting SVG to image in Ionic is successful on Android devices, but the image gets cut off when viewed on

I am facing an issue with exporting an SVG as a base64 encoded image and sending it to the server for storage on Google Cloud Storage. The process works fine on Android and in browsers, but fails when attempted on a physical device running IOS. On IOS, t ...

Disallow/bound the position of the marker on Google Maps

Is there a way to restrict the placement of markers on a map? I am looking for a solution that allows me to limit the marker position within a specific area, such as a town, with a radius of 10km. It should prevent users from dragging or creating new mark ...

"Utilize the power of the ajaxform jQuery plugin to automatically reset form fields

Initially, I'd like to emphasize that this is an original inquiry. My predicament is as follows: I have a chatroom php script where I utilize the ajaxForm jQuery plugin to seamlessly send new messages without having to reload the entire page. Howev ...

Is there a way to create a "navigate to" button directly from the text within a <p> element?

Within my HTML, there is a <p> tag which dynamically receives a link value from a JavaScript function. The link could be anything from www.google.com to youtube or instagram. How can I utilize the "copytoclipboard" library to copy this link to clipbo ...

Formik QR code reader button that triggers its own submission

I recently developed a custom QR code reader feature as a button within the Formik component customTextInput.tsx, but I encountered an issue where clicking on the button would trigger a submission without any value present. The following code snippet show ...

Javascript in Chrome can be used to initiate and conclude profiling

Is there a way to activate the CPU Profiler in the Chrome developer window using a Javascript call? For example: chrome.cpuprofiler.start(); //perform intensive operation chrome.cpuprofiler.stop(); Currently, my only option is to manually click on "s ...

Exploring the world of two-dimensional arrays in D3 programming

I am interested in visualizing data obtained from the census data API, specifically from the ACS survey. The data is not in a typical JSON format, but rather as a two-dimensional array. It appears like this: [ [ “POPULATION”, “DATE”, ...

Using jQuery .animate() leading to erratic input movements

I am currently utilizing jQuery's .animate() feature to create a smooth animation effect on the width of a <div> element when a child <input> is in focus. Nevertheless, I'm encountering an issue where the input field jumps up and down ...