Refreshing HTTP request in Angular

I am currently working with Angular 5 and have encountered the following issue:

Within my route, I have a parameter called year. The component related to this route is supposed to display data based on the year parameter, which is fetched from a service. Initially, when I navigate to the URL with the year parameter, everything works as expected. However, when I update the year parameter, the component does not reload (as anticipated) and only the ngOnInit() method is called again. In this method, I attempt to reload the data by invoking the service method with the new year, but it does not function properly. Below is the code snippet:

test.component.ts:

public ngOnInit() {
    this.route.paramMap.subscribe( params => {
        if (params.has('year')) {
            this.loadData(params.get('year'));
        } else {
            this.loadData();
        }
    });
}

public loadData(year?: string): void {
    this.testService.getData(year).subscribe(data => {
        // edit and assign to variables
    });
}

test.service.ts:

public getData(year) {
    return Observable.forkJoin(
        this.getPart1(year),
        this.getPart2(year)
    );
}

private getPart1(year): Observable<CustomObject[]> {
    let url = this.baseUrl;
    if (year) url = url.concat("?year=" + year);
    return this.http.get<CustomObject[]>(url, httpOptions).pipe(
        catchError(this.handleError<CustomObject[]>())
    )
}

private getPart2(year): Observable<OtherCustomObject[]> {
    let url = this.baseUrl + '/path';
    if (year) url = url.concat("?year=" + year);
    return this.http.get<OtherCustomObject[]>(url, httpOptions).pipe(
        catchError(this.handleError<OtherCustomObject[]>())
    )
}

Is there a way to force the Observable to reload the HTTP request? I attempted using a (Replay)Subject instead of Observables, but it did not yield the desired outcome.

Any assistance on this matter would be greatly appreciated :)

Answer №1

If you want to implement a data reload mechanism in Angular, you can use a combination of BehaviorSubject and switchMap:

//Initialize a BehaviorSubject for reloading data
reloader$ = new BehaviorSubject(null);

//Use switchMap to trigger data reload based on reloader$
public fetchData(year) {
    return this.reloader$.switchMap(() => Observable.forkJoin(
        this.fetchPart1(year),
        this.fetchPart2(year)
    ));
}

Since we are using a BehaviorSubject, the initial call will be smooth with a default value of null.

To trigger the data reload, create a simple reload() method:

public reload(){
  this.reloader$.next(null);
}

By calling reload(), a new value will be emitted by reloader$, causing the observable chain to be executed again and fetching fresh data.

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

Error encountered in AppModule: ComponentFactoryResolver provider not found in StaticInjector

My rails 5.2.0 webpacker app is up and running smoothly, incorporating a basic angularjs app booted via the angular AppModule using UpgradeModule.bootstrap function. Prior to transitioning into a hybrid app, I made sure that the angular app was functionin ...

What advantages does utilizing Angular services for API calls provide?

What purpose does the Angular service serve when making HTTP requests or API calls to the backend, and what are the advantages of using it? ...

Filtering an observable using criteria from another source

I'm currently facing a challenge where I need to map observables by filtering them based on events emitted from other observables. The main question at hand is: Is there a way to pass a property of an event to a filter function? In the following exa ...

Efficiently process and handle the responses from Promise.all for every API call, then save the retrieved data

Currently, I am passing three API calls to Promise.all. Each API call requires a separate error handler and data storage in its own corresponding object. If I pass test4 to Promise.all, how can I automatically generate its own error and store the data in ...

What are some effective methods for troubleshooting Vue.js computed properties and templates?

I am facing challenges with debugging in Vue.js, especially when it comes to debugging computed properties or data values in templates. Currently, I am using the IIFE method for debugging as shown in : <h2 dir="auto"> {{(function(){debugger;let ...

React Material Select: The error is caused by the property 'renderValue' with an expected type, as declared within the 'IntrinsicAttributes & SelectProps' type

Encountering an error with React Material Select, specifically on the Render Value function. How can I resolve this issue while using TypeScript? What should be added to the renderValue line? Error: Type '(selected: Array<number>) => string& ...

What is the solution to the error message "Uncaught TypeError: createTheme_default is not a function"?

While working on my react application with vite, typescript, and mui, I encountered the following error: enter image description here This issue seems to be connected to material ui. Sometimes, deleting the 'deps' folder in '\node_mod ...

Assign the chosen option in the Angular 2 dropdown menu to a specific value

Currently, I am utilizing FormBuilder in order to input values into a database. this.formUser = this._form.group({ "firstName": new FormControl('', [Validators.required]), "lastName": new FormControl('', [Validators.required]), ...

The functionality of Layout.tsx is inconsistent across various pages

I'm having trouble with the console.log() code to display the page path only showing up in the "pages.tsx" file (src/app/pages.tsx) and not appearing in the console for other files located in (src/page/Login). Here is the code from layout.tsx: ' ...

Utilizing a segment of one interface within another interface is the most effective method

In my current project using nextjs and typescript, I have defined two interfaces as shown below: export interface IAccordion { accordionItems: { id: string | number; title: string | React.ReactElement; content: string | React. ...

How do I design a reactive form in Angular 8 that dynamically selects another dropdown option based on the selection of one dropdown?

I am a beginner in Angular and currently working on creating a reactive form. I want to have a functionality where selecting one value in a dropdown menu will automatically populate another dropdown menu with relevant data. Here is the object structure tha ...

Angular 2 Cordova application experiencing challenges with updating member variables that are not reflecting changes in the associated template

In my Cordova app with Angular 2, I am facing an issue where the @Component decorated AppComponent class member variable is not updating in the view template as expected. I have noticed that the first update to the member variable gets rendered in the vie ...

Enhance the background property in createMuiTheme of Material-UI by incorporating additional properties using Typescript

I've been attempting to include a new property within createMuiTheme, but Typescript is not allowing me to do so. I followed the instructions provided here: https://next.material-ui.com/guides/typescript/#customization-of-theme I created a .ts file ...

After installing Microsoft.AspNetCore.SpaTemplates::*, the Angular template seems to be missing

Today I decided to start using .Net and successfully installed the SDK. Following instructions, I ran the CLI command to install the SPA template: dotnet new --install Microsoft.AspNetCore.SpaTemplates::* Although the command ran without any errors, I co ...

Managing state on the login page functions properly, although there is a minor inconvenience of having to click the login button twice after entering the username and password

In Login.tsx, I store user/pass info in a useState called login and pass it up to App.tsx. I then store the access property from login useState to access useState inside App.tsx. While this does technically work, there is an issue where it seems to be one ...

Removing AWS-CDK Pipelines Stacks Across Multiple Accounts

Currently, I am utilizing pipelines in aws-cdk to streamline the process of automating builds and deployments across various accounts. However, I have encountered an issue where upon destroying the pipeline or stacks within it, the respective stacks are ...

strategies for chaining together multiple observables with varying data types and operations

Hey everyone! I'm facing a situation where I have a form with multiple select types, and the options for these inputs are coming from an API. I then take the data emitted from the HTTP request observable and feed it into my FormGroup, and everything i ...

Could someone please clarify whether environment variables are suitable for my specific situation?

As I explore the functionality of environment variables in a production setting following deployment, I find myself curious about how they operate. Operating frontend and backend applications on the same server behind a VLAN can present challenges when sp ...

Vue3 and Typescript issue: The property '$el' is not recognized on type 'void'. What is the correct way to access every existing tag type in the DOM?

Currently, I am in the process of migrating a Vue2 project to Vue3 and Typescript. While encountering several unusual errors, one particular issue with $el has me puzzled. I have been attempting to target every <g> tag within the provided template, ...

KeysOfType: Identifying the precise data type of each property

I came across a solution called KeysOfType on a post at : type KeysOfType<T, TProp> = { [P in keyof T]: T[P] extends TProp? P : never }[keyof T]; Here are the interfaces being used: interface SomeInterface { a: number; b: string; } interface A ...