简体   繁体   中英

Caching Component Data in Angular 2 App

I am using observables to load data in my Angular 2 app, and am now trying to figure out how to use the last cached version of the component (what's in local storage) so that when a user clicks on a new tab (leaves the component), and then re-triggers the opening of the component again (returns) - they get the last state of the component.

This is particularly important in this case partly because there are filters on the page that filter the data according to the user's selections. So when they return to the component I want those filters to still be applied to the data.

This is the call that is made from a component, where I subscribe to the observable with Angular's OnInit life cycle hook:

ngOnInit() {
    this.filtersService.getByFilter(this.page, this.pagesize, {
            'services.workflow.status' : 'consulting'
            })
            .subscribe(resRecordsData => {
                this.records = resRecordsData;
            },
            responseRecordsError => this.errorMsg = responseRecordsError);

}

And this is the observable API call from the service:

getByFilter(page, pagesize, body) {
    const headers = new Headers({ 'Content-Type': 'application/json' });
    const options = new RequestOptions({ headers: this.headers });
    return this.http.post
    (`${this.url}${this.ver}/customers/search?apikey=${this.key}&page=${page}&pagesize=${pagesize}`,
    body, options)
        .map((res: Response) => res.json())
        .catch(this.filterErrorHandler);
}
    filterErrorHandler(error: Response) {
    console.error(error);
    return Observable.throw(error.json().error || 'Server error').share();
}

I haven't run into a caching situation like this before for Angular 2. Would it be as simple as doing an if check to see if local storage contains relevant data? Or is there an Angular-specific mechanism I can use to only re-load the component under certain conditions (if the data has changed since the last time the component was opened, for instance)?

There are several options:

1) Use a service. I have a simple example here: https://blogs.msmvps.com/deborahk/build-a-simple-angular-service-to-share-data/

2) Routing parameters. You can specify required, optional, or query parameters. See this for more information: Sending data with route.navigate in Angular 2

3) In your case there is another option which is to add it/re-retrieve it from local storage. But the above two options may perform better.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM