'Keep Same Data When Page Refreshed Angular 6
I'm getting data on button click from WebAPI and navigate the component to other component to show this data and this trick is working fine for me but the issue is when I refresh the page my data is empty, Please provide me some solution or example to keep same data. Thanks in advance
component.ts //where I'm getting data onClick
onSubmit(){
this.departmentService.GetDepartmentSearchResults(this.modelSearch1.value.Department, this.modelSearch1.value.Year, this.modelSearch1.value.No).subscribe(res => {
this.objDepartmentsSearchedResults = res as DepartmentsSearchedResultsModel[];
this.departmentService.objDepartmentsSearchedResults = this.objDepartmentsSearchedResults;
this._router.navigate(['departments/search-results']);
});
}
service.ts //where I'm passing data to varaible
objDepartmentsSearchedResults: DepartmentsSearchedResultsModel[];
Other component.ts //where I want to show this data
ngOnInit(){
console.log("results listing : ", this.departmentServices.objDepartmentsSearchedResults);
}
Solution 1:[1]
You can use something called localStorage which allows you to save your data in any component and use it in any other component.
So in your case, you can just put the data of the form in local storage and use it in another component.
Please refer this on how to use it.
Solution 2:[2]
You can use localStorage/sessionStorage to store and retrieve data.
But, best approach is to fulfill a route(page) data from the same page itself.
Let's say you are routing from
items(ItemListComponent) --> items/:id(ItemDetailsComponent)
You can pass item data associated with an id from items page (ItemListComponent). So ItemDetailsComponent may not need an additional call to get data.
- If the
items/:idis loaded directly(by someone else) or refreshed, the data passed fromitemspage is lost. - So you have to have a condition to fetch the data if passed in data is undefined. You can do that since all you need is
:id, that you already have as route param
As per your example consider passing Department, Year, No as route query params. If the data is passed from previous page, use that. Else do a server call with those query params(on refresh or when the page is loaded directly when someone else access that route)
page1.component.ts
onSubmit(){
const {Department, Year, No} = this.modelSearch1.value;
this._router.navigate([`departments/search-results?department=${Department}&year=${Year}&no=${No}`]);
}
page2.component.ts
ngOnInit(){
this.activatedRoute.queryParams.subscribe(params => {
const Department = params.get('department');
const Year = params.get('year');
const No = params.get('no');
// make departmentServices call to get data
...
});
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Akshat katiyar |
| Solution 2 |
