What is the process for refreshing one observable with data from another observable?

As a complete beginner to these technologies, please bear with me if my question sounds strange and the terminology is not quite right.

I have a component that displays data in a table format.

export class SourceFieldComponent implements OnInit {
    ...
    componentState$: Observable<ComponentState<SourceFieldResponse>>;
    fileUploadState$: Observable<FileUploadState>;
    ...

    ngOnInit(): void {
      ...
      this.componentState$ = this.sourceFieldService.sourcesFieldsByDataSource$(this.dataSourceId)
            .pipe(
                map(response => {
                    this.currentData.next(response)
                    return { dataState: DataState.LOADED_STATE, appData: response }
                }),
                startWith({ dataState: DataState.LOADING_STATE, appData: null }),
                catchError((error: string) => {
                    return of({ dataState: DataState.ERROR_STATE, error: error })
                })
            );
       ...
    }


    onFileSelected(event) {
       ...
        this.fileUploadState$ = this.fileUploadService.uploadFile$(formData)
            .pipe(
                map(response => {
                    if (response.statusCode != this.RESPONSE_OK) {
                        return { uploadState: UploadState.ERROR_STATE, error: response.message }
                    }
                    return { uploadState: UploadState.LOADED_STATE, error: response.message }
                }),
                startWith({ uploadState: UploadState.LOADED_STATE }),
                catchError((error: string) => {
                    return of({ uploadState: UploadState.ERROR_STATE, error: error })
                })
            )
       ...
    }
}

Whenever a new file is uploaded from the browser, the onFileSelected method is triggered and the file gets successfully uploaded to the backend.

The issue arises when the backend service responds, as I need to refresh the table displaying the data (new records are created from the uploaded file).

It seems like I need to somehow 'refresh' the componentState$ observable but I am unsure how to proceed.

I have attempted some solutions, but none seem to work effectively.

Answer №1

If you're looking for a way to tackle this issue with a reactive approach, consider diving into the world of "Thinking Reactively". I highly recommend checking out two insightful talks on YouTube given by Deborah Kurata and Ben Lesh (who is the project lead of RxJS).

Take a look at these links to their talks: Talk 1: https://www.youtube.com/watch?v=3LKMwkuK0ZE Talk 2: https://www.youtube.com/watch?v=CZYAph73mnI&t=966s

Now, let's shift our focus back to finding a solution.

The core concept of the solution revolves around using subjects (Link to subject documentation). Another option worth exploring is behavior subjects, so feel free to explore that further on your own. The key point here is that a subject is an object similar to an observable that can be subscribed to and emit values or errors.

To see a simplified version of the solution in action, check out this stackblitz demo: Stackblitz Demo Link

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

esLint throws an error advising that a for-in loop should be enclosed within an if statement in order to exclude unnecessary properties from the prototype

While working on my Angular project, I encountered an error with esLint related to the code snippet below: private calculateFieldValue(value: any): any { let isEmptyObject = false; if (value && Array.isArray(value) & ...

Exploring nested static properties within TypeScript class structures

Check out this piece of code: class Hey { static a: string static b: string static c: string static setABC(a: string, b: string, c: string) { this.a = a this.b = b this.c = c return this } } class A { static prop1: Hey static ...

Having trouble sending HTTP requests in Angular 6

I am currently facing an issue in my Angular application while trying to send an HTTP POST request to a Spring RESTful API. Despite my attempts, I have not been able to succeed and I do not see any error response in the browser console. Below is a snippet ...

ng2-auto-complete automatically selects default option on a reactive form

I'm currently integrating https://www.npmjs.com/package/ng2-auto-complete into my Angular 5 application and here's how my input is set up: HTML: <input id="shipper" type="text" class="form-control" for ...

I am encountering an issue where Typescript paths specified in the tsConfig.app.json file are not resolving properly

I have defined path settings in my tsconfig.app.json file like this: "paths": { "@app/core": ["./src/app/core"] } Every time I run a test that includes import statements with relative paths, it throws the following error: ...

What methods exist for creating visual representations of data from a table without relying on plotting libraries?

Is there a way to plot graphs directly from a Data Table without the need for external graph libraries like plotly or highcharts? Ideally, I am looking for a solution similar to ag-grid where the functionality comes built-in without requiring manual code ...

Can someone explain how to create a Function type in Typescript that enforces specific parameters?

Encountering an issue with combineReducers not being strict enough raises uncertainty about how to approach it: interface Action { type: any; } type Reducer<S> = (state: S, action: Action) => S; const reducer: Reducer<string> = (state: ...

Enroll in a stream of data while iterating through a loop in an Angular application

I encounter a situation where I must subscribe to an Observable, iterate through the response, and then subscribe to another Observable using data from the initial Observable. getTasks(taskType: Observable<any>): void { taskType // Subscribing ...

Utilize a function to wrap the setup and teardown code in Jest

I am attempting to streamline some common setup and teardown code within a function as shown below: export function testWithModalLifecycle() { beforeEach(() => { const modalRootDom = document.createElement('div') modalRootDom.id = M ...

Issues arise when attempting to utilize Node.js Socket.io on localhost, as the calls are ineffective in performing logging, emitting, generating errors, or executing any other actions. It has been noted that

I am in the process of developing a real-time socket.io application using Angular and Node, following the instructions provided here. I have set up the server and client connection, but unfortunately, the connection is not being established. Server Code: ...

This TypeScript error occurs when the type of a CSS file lacks an index signature, resulting in an implicit 'any' type for the element

Currently in the process of transitioning a React app to utilize Typescript. Encountering an error message that reads: ERROR in [at-loader] ./src/components/Services/Services.tsx:34:29 TS7017: Element implicitly has an 'any' type because typ ...

The test failed to execute due to disconnection (0 occurrences) as no message was received within the 30000 ms timeframe

Currently, I am facing an issue with my Angular application. When I execute the "ng test" command, it displays an error message stating 'Disconnected (0 times), because no message in 30000 ms.' I have tried updating both karma and jasmine package ...

Is it possible to eliminate a parameter when the generic type 'T' is equal to 'void'?

In the code snippet below, I am attempting to specify the type of the resolve callback. Initially: Generic Approach export interface PromiseHandler<T> { resolve: (result: T) => void // <----- My query is about this line reject: (error: a ...

Implementing try-catch logic for element visibility in Playwright using TypeScript poses limitations

There is a specific scenario I need to automate where if the title of a page is "Sample title", then I must mark the test as successful. Otherwise, if that condition is not met, I have to interact with another element on the page and verify if the title ch ...

Is Typescript compatible with the AWS Amplify Express API?

I've been struggling to set up my Amplify API in TypeScript and then transpile it to JavaScript. I know it sounds like a simple process, but I could really use some guidance on how to do this effectively. So far, I haven't progressed beyond the ...

Expanding the MatBottomSheet's Width: A Guide

The CSS provided above is specifically for increasing the height of an element, but not its width: .mat-bottom-sheet-container { min-height: 100vh; min-width: 100vw; margin-top: 80px; } Does anyone have a solution for expanding the width of MatBott ...

Just starting out with React and encountering the error: Invalid element type, a string was expected

I seem to be going in circles with the following issue as I try to load the basics of a React app into the browser. An error message stating 'Element type is invalid: expected a string (for built-in components) or a class/function (for composite c ...

CreateAsyncModule using an import statement from a variable

When trying to load a component using defineAsyncComponent, the component name that should be rendered is retrieved from the backend. I have created a function specifically for loading the component. const defineAsyncComponentByName = (componentName: strin ...

Ways to verify if a function has completed execution and proceed to invoke another function

I am seeking to verify if a user has chosen an item from the ngFor form and then redirect them to another page upon submitting the form with the updated value. HTML: <mat-select placeholder="Treatment" [(ngModel)]="model.TreatmentA" name="TreatmentA" ...

Is it possible to create a prototype function within an interface that can group items in an array by a specific property, resulting in an array of objects containing a key and corresponding array of values?

I've been working on this code snippet and I'm trying to figure out how to make it work: Array<T>.groupBy<KeyType> (property): {key: KeyType, array: Array<T> }[]; The code looks like this: type ArrayByParameter<T, KeyType = ...