Is it necessary to use ReplaySubject after using location.back() in Angular 6 to avoid requesting data multiple times?

I'm currently utilizing a BehaviorSubject in my service to retrieve data from the BackEnd, which I subscribe to in my mainComponent using the async pipe.

However, whenever I navigate to another subComponent and then return to my mainComponent by clicking a back button (which triggers Location.back()), it always performs a new request to fetch all the data from the BackEnd.

I suspect this behavior is due to the async pipe unsubscribing from the BehaviorSubject when exiting the mainComponent.

Is there a need to implement a caching strategy for this issue? Or can it be resolved by using a ReplaySubject with the size of the data fetched from the mainComponent?

Below is an excerpt of my code:

Service:

private subject$: BehaviorSubject<Setting[]> = new BehaviorSubject<Setting[]>([]);

fetchData() {
  const fetch$: Observable <Setting[]> = this.getSettings().pipe(share());
  fetch$.pipe(
      map(allSettings => this.subject$.next(allSettings))
    );
  return fetch$;
}

MainComponent:

data: Observable<Setting[]>;

// Load Setting while starting
ngOnInit() {
  this.data = this.apiService.fetchData();
}

MainComponent.html:

<tr *ngFor="let s of data | async">
  <!--Do Something...-->
</tr>

SubComponent:

goBack(): void {
  this.location.back();
}

Appreciate any assistance on this matter :)

Answer №1

When you revisit the component, any code within ngOnInit() will run again. One approach is to store your data in a service and then in ngOnInit(), check if the service already holds the data. If it does, there's no need to fetch it from the server again.

if(myservice.data) {
do nothing}
else {
myservice.data = this.apiService.fetchData();}

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

Dealing with the endless looping problem in Next.js caused by useEffect

Looking to implement a preloader that spins while the content is loading and disappears once the loading is complete. However, encountering an issue where the site gets stuck on the loading page and keeps loading infinitely. I've tried multiple soluti ...

Tips for testing nested subscribe methods in Angular unit testing

FunctionToTest() { this.someService.method1().subscribe((response) => { if (response.Success) { this.someService.method2().subscribe((res) => { this.anotherService.method3(); }) } }); } Consider the following scenario. ...

What is the best way to display noscript content within my Angular application?

What is the best way to show HTML content for users who do not have JavaScript enabled in my Angular application? Inserting the noscript tag directly into the index.html file does not seem to be effective. <body> <noscript>Test</noscrip ...

The http post request is functioning properly in postman, but it is not working within the ionic app

I am currently developing an app in ionic v3 within visual studio (Tools for Apache Cordova). On one of the screens in my app, I gather user information and send it to an API. However, I'm encountering an issue with the HTTP POST request that I'm ...

Angular Material datetime picker with an option for transparent background

After upgrading my angular from version 15 to 16, I encountered a strange issue with the material date time picker. The GUI part of the picker appeared half transparent as shown in this image: Has anyone else faced this kind of problem with the material d ...

I encountered an issue where I could not successfully update a list pushed into an array using the push function. Despite attempting to update the list, I

export class ApproveComponent implements OnInit { @Output() public next: EventEmitter<any> = new EventEmitter<any>(); codes: any[] = []; selectedCode: any; this.Apiservice.komm.subscribe(data => { this.se ...

Making an Http Get request in Angular 2 by passing a JSON object

How can I make an HTTP GET request and send a JSON object along with it? Here is the JSON object: {{firstname:"Peter", lastname:"Test"} I want to pass this object in the HTTP request to receive a list of matched persons. Is this possible? The example o ...

Resolve the result of the HttpComponent within the Service component

Consider this example involving HttpClient: In Service configData: string[]; fetchData(): Observable<string[]> { return this.http.get<string[]>('./assets/config.json'); } getConfigValue(key: string): string { if ...

Combining ngModel and ngClass in Angular: a comprehensive guide

I have implemented the following code in Angular 6 using Visual Studio Code <div [ngClass]="{'disabled': isReadOnly}"> <label class="switch"> <input type="checkbox" name="Gender" ...

Encountering the Selenium Webdriver HTTP error within an Angular 4 project

ERROR Detected Issue found in: ./node_modules/selenium-webdriver/http/index.js Module not found: Error: Unable to locate 'http' in 'C:\Users\aprajita.singh\Documents\Angular 4\Auto-Trender-Project\node_modules ...

Refresh the display after adding an item to an array in Angular

Currently, I am facing an issue with updating the view based on adding an item to an array of objects through a click handler. While the item is successfully pushed into the array, it does not reflect in the view. I am wondering if placing the method withi ...

Retrieve the current number of displayed items from Ngx-Datatable

I have been utilizing swimlane/ngx-datatables in combination with Angular5. I am interested in incorporating a new footer that showcases the current display count. https://github.com/swimlane/ngx-datatable Here is my desired format for the footer: Showing ...

Differences between useFormState and useForm in Next.js version 14

Currently, I am intrigued by the comparison between using the react hook useForm and the react-dom useFormState. The Nextjs documentation suggests utilizing useFormState, but in practice, many developers opt for the react hook useForm. I am grappling with ...

Encountered a Runtime Error: Uncaught promise rejection - couldn't locate removeView

I am facing an issue with calling two API calls on the same page. When I use only one API call, everything works fine. However, when I try to make two API calls on the same page, I encounter the following error at runtime: Error Uncaught (in promise): r ...

What is the best way to send requests to an API server without directly specifying the URL in the code?

As I work on implementing an app using Angular 2, I find myself needing to make requests to my API server. However, hardcoding the full URL in every request doesn't seem like a good idea since it's likely to change. While researching a solution, ...

How to effectively utilize TypeScript in a team environment using both Atom and VSCode?

Our team utilizes TypeScript with both Atom and VSCode as our editors, but we are facing challenges with the tsconfig.json file. VSCode is not recognizing the typings, causing the namespace for 'ng' (for Angular 1.x) to be unknown in VSCode. Wh ...

The process of retrieving data from Firebase Firestore

Here is the content of my HTML File: <div class="container m-3 p-3"> <h1>Current Items</h1> <ul class="list-group"> <li class="list-group-item">An item</li> <li class="list-gro ...

The compiler error TS2304 is indicating that it cannot locate the declaration for the term 'OnInit'

I successfully completed the Angular superhero tutorial and everything was functioning properly. However, when I close the CMD window running NPM and then reopen a new CMD window to reissue the NPM START command, I encounter two errors: src/app/DashBoard ...

When invoking the function, the original state remains unaffected within a separate function

Whenever I click on an 'item', it should establish an initial value for me to use in a comparison within another function that involves the mousemove event. However, when the mousemove function is triggered, the initial state remains at 0. imp ...

Encountering an obscure package error while attempting to install an NPM package

After running the following command on my node application: npm install --save-dev typescript I encountered this error message: > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="563a3f3426271667786e786e">[email pro ...