I have a query that pulls in data from my database using appollo-angular. What would be the best practise way to share this data between componenets. I saw that it was mentioned using a shared service and subscribing in each component. Would this method take into account data updates as currently I’m querying and grabbing the data again every single time:
Inside service:
private data = new BehaviorSubject(null);
currentData = this.data.asObservable();
getDataFromDB(): Observable<any> {
return this.apollo.watchQuery<any>({
fetchPolicy: 'cache-first',
query: DataQuery,
}).valueChanges.pipe(
tap((res: any) => {
this.dataFromDB.next(res.data.dataFromDB);
})
);
}
Inside componenet1:
constructor(private dataService: DataService) {
ngOnInit(): void {
this.dataService.currentData.subscribe(queryData => {
this.data = queryData;
});
}
It was previously querying the data everytime the component was loaded but I’m looking to see how to optimize this and have tried setting up a service but not sure If I’m approaching it correctly
Jeremiah Mark is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.