Reputation:
On my first Home Component, on ngOnInit I call a function that subscribes results to a variable and displays those results :
ngOnInit() {
this.dataService.getAllData().subscribe(results =>
this.userData = results.userData;
}
On my HTML I have a function where I need to remove some elements from the array :
this.userData.splice(this.removedIndex, 1)
When navigating away from that screen, and coming back, because of ngOnInit, the userData will have ALL the data from the service again and I need to have only the data remaining after the splice. Once logging out and logging back in, then all data can be displayed. Is there a way to achieve this? Any suggestions?
Thanks.
Upvotes: 0
Views: 4144
Reputation: 421
2.create a service and inject in your app.module.ts So that all your components share the same instance of the service
Upvotes: 0
Reputation: 19578
Keep the data on a service, not locally. It can be something as simple as:
class DataHoldingService {
data$ = new BehaviorSubject<any[]>([1, 2, 3, 4]);
// or get from, say, backend:
constructor() {
this.backend.getData().subscribe(data => this.data$.next(data));
}
}
Then your component gets this on init:
class MyComponent {
myData: any[];
constructor(private dataService: MyDataService) {}
ngOnInit() {
this.dataService.data$.subscribe(data => this.data = data);
}
// when removing that index:
removeData(index: number) {
this.data.splice(index, 1);
this.dataService.next(this.data);
}
}
This way, when your component removes the index, you'll have the updated data on the service as well as locally.
To survive full page reloads, you need a bit more. Here's a naive example:
class DataHoldingService {
data$: new Observable<any[]>;
private dataObserver: Observer;
constructor() {
this.data$ = new Observable(observer => {
this.dataObserver = observer;
this.loadInitialData();
});
}
setData(data) {
localStorage.setItem('data', JSON.stringify(data));
this.dataObserver.next(data);
}
loadInitialData() {
let data = [];
try {
data = JSON.parse(localStorage.getItem('data'));
} catch (e) {
/* no data */
}
this.dataObserver.next(data);
}
Of course, now your component can't call next()
but has to use setData()
:
class MyComponent {
// other stuff is the same
// removing that item, or adding or whatever
removeItem(index: number) {
this.data.splice(index, 1);
this.dataService.setData(data);
}
}
Now your data service will always keep a copy of the data in localStorage. So even if you refresh the page, you still get the edited data. You still need to manage the lifecycle of it all (load data from backend, you may need to conditionally do that initial load, cleanup on login/logout etc).
Upvotes: 2