What is the best way to extract information from an observable and apply it in another function?

I have a function that looks like this:

public getAssemblyTree(id: number) {

        ....

         const request = from(fetch(targetUrl.toString(), { headers: { 'responseType': 'json' }, method: 'GET' }));

                request.subscribe(
                    (response) => {
                        response.json().then(data => {
                            (this.parseAssemblyTree(data['flat_assembly_graph']));
                        }
                        )
                    }
                )
    
public updateAssemblyTree(id: number) {
            let res = this.getAssemblyTree(id)
            this.asmTree.next(res);
        }
    

I need the data returned once the observable completes by the first function to be stored in the variable "res" in the second function (public updateAssemblyTree(id: number)). Can someone provide guidance on how to achieve this? I am new to using observables, so having the code written out would greatly assist me. Thank you all for your help in advance :)

Answer №1

If you have a function called getAssemblyTree that returns an observable or promise, you can easily subscribe to it like this:

this.getAssemblyTree(id).pipe(takeUntil(this.componentDestroyed$))
.subscribe((response) => {
    if(response) {
        //implement your logic here.
    }
}).

The variable this.componentDestroyed is declared as

private componentDestroyed$ = new Subject<void>();

Don't forget to clean up in the ngOnDestroy method of your component:

this.componentDestroyed$.next();
this.componentDestroyed$.complete();

What's happening here is that your component will continue to react to changes in the getAssesmblyTree function as long as the component remains active. This approach works well with Observables or promises (you can convert a promise to an Observable using 'from').

Edit: For more advanced scenarios, consider using a store to manage state and subscribe to specific parts of it. This pairs nicely with async pipes.

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

What is the best way to connect to a JSON key that is consistently returned with a varying or unpredictable name?

I am currently working on an Angular 4.x application where my goal is to showcase a random Wikipedia article. Each time I check the JSON data in Chrome Dev Tools under query/pages, I notice that the pageID always has a different number. The structure of th ...

Exploring Angular's View Encapsulation with Third-Party Libraries

When I integrate an external component into my own, I face a challenge with styling due to Angular View Encapsulation. Any CSS I define in my component does not affect the external component used in my HTML template. To work around this issue, I have set e ...

Unexpected INTERNAL error encountered with Firebase's Cloud Function update

Currently, I am immersed in a project involving Vue.js 3, Typescript, and Firebase. However, while attempting to integrate new cloud functions, I came across an unexpected issue: Failed to load resource: the server responded with a status of 500 () Un ...

Issue with Material UI: Style overrides for nested components are not being applied

Having recently delved into CSS in JS techniques, I've hit a roadblock when it comes to styling components in Material UI, particularly with overriding styles of nested elements. Although I have been referring to the official documentation, I still fi ...

Display or conceal list elements using Angular directives in the HTML

I currently have a lineup of 4 items, with the initial 2 visible and the latter half hidden. There's also a button labeled "expand / collapse" that alters the visibility of the final 2 items. <ul> <li>Item 1</li> <li>Item 2 ...

Iterate through the AJAX response and update each element that has a designated ID

I am trying to iterate through each object in an AJAX response and add HTML containing the data to a div with the ID #jobs. $.ajax({ url: '/browse_jobs', data: { 'keyword': keyword, }, dataType: 'json', success: ...

Iron-localstorage in Polymer 2.0 now supports storing and managing two distinct arrays

Looking for help with creating a shopping cart using Polymer. I'm struggling to insert selected data from the template dom-repeat into an array bound to iron-localstorage (e.model.item) and it's not working. <dom-module id="shop-cart"> < ...

Strategies for managing database modifications in a MEAN stack project

Online resources are scarce on this topic, but I am facing a common issue in application development. My project involves multiple users accessing and editing a shared database simultaneously. The challenge is ensuring that all users have an accurate and ...

The functionality of jQuery's toggleClass is not functioning properly when clicking on a different thumbnail

My objective: I want to display a set of thumbnails. When a thumbnail is clicked, I want to toggle the hiddenElement class and show a large image inside a hidden div. If anywhere in the DOM is clicked, it should hide the current image or allow the user t ...

Using JavaScript code to sift through and eliminate irrelevant data

Recently, I started learning about angular js and came across a link from which I need to extract a list of names and ids. I successfully retrieved the list in json format, but now I need to filter out unwanted items. The criteria for filtering is based ...

I'm looking to integrate language switching into my Angular application with the help of the official Angular i18n library. How can I

In order to enable language switching in my Angular application, I am looking to utilize the official Angular i18n library. This decision comes as a result of the previous go-to library (ngx-translate) being put into maintenance mode and scheduled for depr ...

Converting an array of strings into a JSON object using JavaScript

Below is an array that needs to be transformed into a JSON object: data = [ "Id = 2", "time = 10:59", "Topic = xxxxxxxxxxxxxxxx", "GUEST3", "Role = GS", "Infos = Connecticut", "GUEST4", "Role = HS", "Infos = Delaware", ...

Angular2+ test case indicating lack of NgControl provider

I've been facing an issue while testing an angular component with multiple dependencies. The test case fails with the error: "No Provider for NgControl". Here's the detailed error message: Chrome 66.0.3359 (Mac OS X 10.13.4) configurator compone ...

The Kendo Date Picker is failing to update properly when the k-ng-model is modified

I am facing an issue with my code involving two date pickers and one dropdown list. I want the date pickers to change based on the selected item from the dropdown list. Here is the relevant portion of my code: $scope.toolbarOptions = { i ...

Tips for integrating AsyncGenerators with Kotlin/JS

I am currently exploring the use of IPFS with Kotlin/JS, but my issue is not limited to that specific context. The functions ipfs.cat() and ipfs.get() return an AsyncGenerator, and I am uncertain about how to properly iterate over it using Kotlin (I am als ...

The JSON GET method displays HTML content when accessed through code or console, but presents a JSON object when accessed through a web address

I am currently trying to execute the following code: $(document).ready(function () { $.ajax({ url: 'http://foodfetch.us/OrderApi/locations', type: 'GET', success: function(data){ alert(data); ...

Merge the results of two MongoDB queries

Currently working with node.js and express, I'm trying to merge and then display the results of two mongodb queries from separate collections. The collections contain data for different users, and my goal is to showcase all user data in a single list. ...

A guide to organizing page components across multiple `/pages` directories in a Next.js application

As I delve into my first project using Next.js, I find that my pages directory has expanded significantly. Now, I am keen on organizing my pages by grouping them into modules, resulting in a structure like 'src/modules/*/pages/*'. In my quest fo ...

Eliminating Angular's @Injectable decorator in npm build process

I have encountered a setback while working on a small helper package for Angular. The issue I am facing is related to an exported class that serves as an Angular service and is decorated with @Injectable(). After running npm run build, the compiled class ...

Dynamic horizontal scrolling

I need help implementing a site using React that scrolls horizontally. I'm unsure how to implement certain aspects, so I am looking for some assistance. Within a wrapper, I have multiple container Divs. <div class="wrapper"> <div class=" ...