1

I have two angular components. The first component has a list with picture items requested from a server. When the user selects one picture he is forwarded to the second page, the detail view, where more information is displayed. Now when he is hitting the browser's back button component 1 loads again and fires some heavy request for getting the pictures.

Is there a way I can cache component 1 so when the user hits the browser's back button component 1 is restored and the server request are not sendend again? I have read about Angular Route Reuse Strategy but I guess this applies not for browser navigation?

1
  • 1
    If your http call is done from a service (so not inside the component itself), the service will stay alive and you can easily do a shareReplay on the observable. That will prevent the call a second time and just reuse the previously emitted value. Commented Jul 14, 2020 at 14:30

3 Answers 3

0

Just store the items in a variable inside a service

Sign up to request clarification or add additional context in comments.

Comments

0

Use a RouteReuseStrategy

https://angular.io/api/router/RouteReuseStrategy

It allows to cache entire components and when you hit the back button, the cached component is restored and no requests are sent again.

This goes in more detail: https://blog.bitsrc.io/angular-route-reuse-strategy-c7939ebbf797

Comments

0

To prevent unnecessary data reloading when navigating back to Component 1, store the data retrieved from the server in a service using a BehaviorSubject. This allows both components to access the stored data and eliminates the need for additional requests. Using a BehaviorSubject ensures components always have the most recent data.

This approach improves user experience by avoiding unnecessary server requests and resulting in a faster, more efficient system.

For example:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { BehaviorSubject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class PictureService {
  private pictureData = new BehaviorSubject<YOURPICTUREDATATYPE | null>(null);

  constructor(private http: HttpClient) { }

  getPictureData() {
    return this.pictureData.asObservable();
  }

  loadPictureData() {
    this.http.get('https://example.com/picture-data').subscribe((data: any) => {
      this.pictureData.next(data);
    });
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.