Employing an unchanging Map format for observation

I'm currently working on implementing a synchronization mechanism using observable and Map structures from Immutable.js.

However, I'm encountering an issue where the Map is unable to function as an observable or perhaps I might be approaching it incorrectly.

I've explored the Rx documentation and tried various methods like just, return, from, of... but none seem to align with using a Map.

What I really need is to ensure that my Map is fully populated (with values retrieved from an http.GET request) before executing the actions in the subscribe callback.


import {List, Map} from 'immutable';
import {Observable} from 'rxjs/Observable';
...

processNewTopology(topology: List<Endpoint>): Observable<Map<string, any>> {

    let ip: string = JSON.stringify(topology.get(0).ueIpAddress);

    //this function makes an http GET request and returns an observable string (imsi)
    this.apiService.getImsiFromAAA(ip).subscribe(
            imsi  => myMap = this.reduceEndpointsToMap( imsi, topology),
            error =>  this.errorMessage = <any>error
          );

    return myMap; // I need to find a way to convert my map into an observable

}


private reduceEndpointsToMap(imsi: string, topology: List<Endpoint>): Map<string, any> {
    // This function takes the imsi and a list of endpoints, builds the map, and returns it
    // The imsi is obtained through an http.GET request
}

In another class, I call processNewTopology to retrieve the Map. It's crucial for me to have the map ready before proceeding with display actions.

this.topologyService.processNewTopology(endpoints).subscribe(
          myMap => {
            // In this section, I aim to access the content of myMap to display the new topology
          }
          ...
        );

Answer №1

If you're utilizing the Obserable as an ES6 Promise, it's recommended to encapsulate the HTTP request from the API service within a Promise for better handling. By wrapping the http request in a Promise, you can easily handle the result once the request has been completed.

API Service:

class TopologyService {

    private apiService: any;

    ...

    public processNewTopology(topology: List<Endpoint>): Promise<Map<string, any>> {
        let ip = JSON.stringify(topology.get(0).ueIpAddress);

        return new Promise((resolve, reject) => {
            this.apiService.getImsiFromAAA(ip).subscribe(
                response => resolve(this.reduceEndpointsToMap(response, topology)),
                error => reject(error)
            );
        });
    }

    private reduceEndpointsToMap(imsi: string, topology: List<Endpoint>): Map<string, any> {
        ...
    }

    ...
}

Example of Usage:

topologyService.processNewTopology(endpoints)
    .then(value => {
        // Perform actions with the value
    })
    .catch(err => {
        // Handle errors that occurred
    });

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

Managing numerous API requests in React Native

As I work on implementing a search field, I've encountered a challenge. Whenever a user enters text in the search field, a timer resets to 300 ms before an API call is sent to fetch autocomplete results. After receiving these results, the app then wai ...

In React using Flow Type, the syntax [...mySet] doesn't function as expected, while Array.from(mySet) successfully converts the

Why is it that with React and Flow Type, the line of code displaying [{}] when using JSON.stringify([...mySet]) but shows the correct values with JSON.stringify(Array.from(mySet))? The issue seems perplexing as this behavior cannot b ...

Transforming a JavaScript object into a different shape

I need help converting a list of team objects containing team names, reporters, and statuses for each day into date-based objects with all teams and their respective statuses for each date. I attempted the following code snippet but did not achieve the de ...

Creating a custom decision tree in Angular/JS/TypeScript: A step-by-step guide

My current project involves designing a user interface that enables users to develop a decision tree through drag-and-drop functionality. I am considering utilizing GoJS, as showcased in this sample: GoJS IVR Tree. However, I am facing challenges in figuri ...

Adding FormControl dynamically to FormGroup can be achieved by simply using the appropriate method

Currently, I am working with a plunker where I am dynamically creating form components based on the model specified in app.ts. However, I am facing an issue where I cannot add formControlName = "name" to the component. In my control-factory.directive.ts ...

Intersection observer automatically removes images from carousel (Siema) after they have been viewed

Check out this example to see the issue I'm facing. I've implemented an intersection observer for lazy loading images, here's the code: const pictures = document.querySelectorAll("[data-src]"); function loadPicture(pic){ const src = p ...

Sending properties of an element to a function within Angular version 4 or 5

Trying to pass attribute values of elements to a function on button click, this is my approach: <div> <ul #list> <li class="radio" *ngFor="let option of options; let j = index" id={{i}}-{{j}} #item> <label><input t ...

Customize the element of the root node of a MUI component using the styled()

I am trying to implement the "component" prop with a MUI component (such as ListItem) using the styled() API. However, I am facing an issue where it says that "component" is not a valid prop. Can someone guide me on how to correctly achieve this? I have se ...

Guide for converting a JavaScript function with spread arguments of different types to C# style

I am having difficulty with the strict typing in C# when it comes to function arguments. For my Reverse Polish Notation (RPN) calculator, the required arguments will be passed through a function call using a comma-separated list of different types: this.F ...

Guide on creating a cookie verification process with no contents

Request for Assistance: let cartHelper = { cartCookieName: "_cart", getCart: function (callback = undefined) { return apiHelper.getRequest( "/carts", (response) => { documen ...

The login page continues to show an error message for incorrect credentials unless the submit button is clicked

My current project involves a React component called "Signin.js". Within this component, there are login input fields as I am working on creating a login system using Node.js, Express.js, and MySQL. To achieve this, I have set up a post request that sends ...

What is the most effective way to use a withLatestFrom within an effect when integrating a selector with props (MemoizedSelectorWithProps) sourced from the action?

I am struggling to utilize a selector with props (of type MemoizedSelectorWithProps) in an effect inside WithLatestFrom. The issue arises because the parameter for the selector (the props) is derived from the action payload, making it difficult for withLat ...

How can I retrieve an array from an object containing both a property and an array in TypeScript?

One of my objects always consists of a property and an array. When I use the console.log(obj) method to print it out, it looks like the following example: ProjectName: MyTest1 [0] { foo: 1, bar: 2} [1] { foo: 3, bar: 4} [2] { foo: 5, bar: 6} Alternat ...

Exploring Azure: Obtain a comprehensive list of application settings from a deployed Node.js web application

After successfully deploying a NodeJs app to a Linux Azure AppService, I am now aiming to retrieve the server settings of this particular app-service. By enabling managed Identity for the AppService under the 'Identity' tab, I attempted to achiev ...

Obtain the Encoded Data

Unfortunately, I do not have control over domain.com. However, I am able to provide a redirect URL parameter like the one shown below: www.domain.com?retUrl=www.example.com%3Fparameter%3Dvalue Following the provision of retURL (www.example.com?parameter= ...

Using setTime in JavaScript allows for customizing and adjusting the

I'm having trouble getting this code to display the time. I thought it would work, but it's not showing the time. Can someone please help me figure out what's going wrong? function startTime() { var currentTime = new Date(); ...

Unable to retrieve HTML content through a Node.js server

I created a HTML webpage that includes .css, images and JavaScript files. However, when I start my node server using the command below: app.get('/', function(req, res){ res.sendFile(__dirname + '/index.html'); }); The webp ...

Removing background from a custom button component in the Ionic 2 navbar

Q) Can someone help me troubleshoot the custom component below to make it resemble a plus sign, inheriting styling from the <ion-buttons> directive? In my navbar, I've included a custom component: <notifications-bell></notifications-be ...

How to sync two carousels in Bootstrap 5 to slide simultaneously with just one click on the next and previous buttons

I am trying to implement dual sliding carousels using Bootstrap 5, but I am encountering issues with getting them to slide simultaneously. Despite incorporating data-bs-target=".carousel", the synchronization isn't working as intended in my ...

Arrange objects in an array according to the order specified in another array

Here is my array of car makes: const makes = [ {id: "4", name: "Audi"}, {id: "5", name: "Bmw"}, {id: "6", name: "Porsche"}, {id: "31", name: "Seat"}, {id: "32", name: "Skoda"}, {id: "36", name: "Toyota"}, {id: "38", name: "Volkswagen"} ] Now, I want to o ...