Imagine a scenario where there is a service used for making HTTP request calls. There are two different components (which could be more than two) that need to send the same request using the same observables via this service. After receiving the result, it should be assigned to a global variable. These components do not have any direct relationship, like parent-child or child-parent. Is there a more efficient way to write this function once and reuse it across all components?
Service
getStudents() {
const requestUrl = this.apiUrl + 'students/';
return this.httpClient.get(requestUrl);
}
Component1
studentList:Student[]=[];
getStudents.subscribe((students:Student[])=>{
this.studentList=students;
//Some operations
})
Component2
studentList:Student[]=[];
getStudents.subscribe((students:Student[])=>{
//Some operations
this.studentList=students;
})