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

Issue encountered while setting up controls and AbstractControls in form development

Here is a snippet of code showing how I create and manipulate a form in Angular: this.myForm = new FormGroup({ points: new FormArray([ new FormGroup({ date: this.date, startTime: new FormControl(null, Val ...

Tips for dynamically altering the data type of an object in Angular depending on a certain condition

I'm currently in the process of developing an online store and facing challenges with integrating a dynamic form system that can adapt based on the type of product being added to the store. For instance, if I select the 'Clothing' category, ...

Obtain the content window using angularJS

I've been attempting to retrieve the content window of an iframe element. My approach in JQuery has been as follows: $('#loginframe')[0].contentWindow However, since I can't use JQuery in Angular, I've been trying to achieve thi ...

What steps can be taken to retrieve error.data from RTK Query while utilizing typescript?

When I log error to the console, this is what I see: { status: 401, data: "Invalid password" } If I attempt to log error.data, an error occurs: The "data" property does not exist in the "FetchBaseQueryError|SerializedErr ...

What is the best way to send multiple parameters to @Directives or @Components in Angular using TypeScript?

I am facing some confusion after creating @Directive as SelectableDirective. Specifically, I am unclear on how to pass multiple values to the custom directive. Despite my extensive search efforts, I have been unable to find a suitable solution using Angula ...

TypeScript failing to correctly deduce the interface from the property

Dealing with TypeScript, I constantly encounter the same "challenge" where I have a list of objects and each object has different properties based on its type. For instance: const widgets = [ {type: 'chart', chartType: 'line'}, {typ ...

How to set the default theme color for the mat-sidenav background in Angular 6 and 7?

Is there a way to make the background of a mat-sidenav match the theme color of my mat-toolbar? In the file src\styles.scss, I have the following: @import '~@angular/material/prebuilt-themes/indigo-pink.css'; The template / HTML file incl ...

Getting foreign key data from Django to display in Angular

Looking to fetch all columns of a table using a foreign key relationship and unsure of the process? Here's the code snippet: models.py class Athletes(models.Model): athlete_id = models.AutoField(db_column="AthleteID", primary_key="True") fir ...

Android layout featuring Ionic2 navbar with icons aligned on both sides at the top

<ion-header> <ion-navbar align-title="center" color="primary" hideBackButton> <ion-buttons ion-button icon-only start class="card-buttons"> <button class="card-buttons" (t ...

Trustpilot Authentication Error: Grant_type Not Recognized

I am attempting to utilize the Trustpilot API for sending email review invitations. Before making the call, I need to obtain an access token as per Trustpilot's documentation. However, when implementing the function below, I am encountering an error i ...

Extracting the base href in Angular 6

Is there a way to dynamically retrieve /CTX-ROOT/assets/tiny-editor/langs/cs.js in Angular 6 component without using the PlatformLocation#getBaseHrefFromDOM method? constructor( private zone: NgZone, private platformLocation: PlatformLocation) ...

What is the best way to manage a debounced event emitter in Cypress using RxJs debounceTime?

My task involves creating tests for a web page containing a list of items and a search-filter feature. The search-filter functions by filtering the list of items based on the input entered into its text field. Whenever the value in the text field changes, ...

What method can be used to inherit the variable type of a class through its constructor

Currently, I am in the process of creating a validator class. Here's what it looks like: class Validator { private path: string; private data: unknown; constructor(path: string, data: string) { this.data = data; this.path = path; } ...

How can we effectively transfer a value from TypeScript/Angular?

I am new to TypeScript and Angular, and I'm struggling with assigning a value to a variable within a function and then using that value outside of the function. In regular JavaScript, I would declare the variable first, define its value in the functio ...

Unit Testing JWT in Angular 2

Using JWT for authentication in my API calls. I am in the process of coding a service method. An interceptor is applied to all requests: public interceptBefore(request: InterceptedRequest): InterceptedRequest { // Modify or obtain information from ...

Uninstalling NPM License Checker version

Utilizing the npm license checker tool found at https://www.npmjs.com/package/license-checker The configuration in license-format.json for the customPath is as follows: { "name": "", "version": false, "description&quo ...

the ngbPopover refuses to appear

I'm attempting to utilize the popover feature from ng-bootstrap in my Angular2/Typescript application, following the guidelines at here. Despite not encountering any errors, I am facing an issue where the popover does not appear. Here is the snippet ...

The local scope in Angular is inaccessible within an observable subscription

I've been grappling with this issue for quite some time and have experimented with numerous solutions. It seems that within my subscribe function, I'm unable to access ChangeDetectorRef or NgZone in order to trigger an update on the scope. Why ...

What steps can be taken to resolve the Angular error stating that the property 'bankCode' is not found on type 'User' while attempting to bind it to ng model?

I'm encountering an issue with my application involving fetching values from MongoDB and displaying them in an Angular table. I've created a user class with properties like name and password, but I keep getting errors saying that the property doe ...

Ways to interpret and fix a conflict in npm dependency and understand the output

I'm encountering some issues while attempting to set up my project. The errors I'm running into during the installation process are: npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While resolving: @angular-devkit/< ...