Tips for preventing repetition in http subscribe blocks across various components

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;
  })

Answer №1

I'm not particularly fond of utilizing global state, however, if the goal is to keep a consistent list of students across various components using global state, then it might be best for that state to reside within a service rather than being scattered among individual components.

For instance:

Service


studentList: Student[] = [];

setStudents(students: Student[]) {
  this.studentList = students;
  // Any actions related to updating student list
}

updateStudents() {
  const requestUrl = this.apiUrl + 'students/';
  return this.httpClient.get(requestUrl).pipe(
    tap(this.setStudents)
  );
}

Component

ngOnInit(){
  this.service.updateStudents().subscribe();
}

Answer №2

One way to handle data flow in your application is by using an Observable inside your service.

studentsReceived:Subject = new Subject();

When the getStundent() method is successful, you can emit the next value of studentsReceived.

By subscribing to the studentsReceived inside your components, you can receive notifications after a successful API call.

studentRecived.subscribe(data=>{ // add your code here })

Remember to call the getStudent() method on a higher component like AppComponent to initiate the data fetching process.

Answer №3

Here are 2 key points to consider:

1) To avoid repeating the same block of code, create a method in the service file and call it in the component. For example:

SERVICE:

createSubscription(componentVariableName) {
  this.yourObservable.subscribe(subscribedValue => {
     componentVariableName = subscribedValue;
  })
}

In your Component:

yourComponentMethod() {
  this.service.createSubscription(this.studentLists);
}


************

2) To minimize service calls, utilize Behavior Subject to store values rather than repeatedly making API calls. Here's an example:

private initialValuesForObservable: YourObjectModel = {}; // or null;

private observableSource: BehaviorSubject<YourObjectModel> = 
  new BehaviorSubject<YourObjectModel>(this.initialValuesForObservable);

public subscribableObservable: Observable<YourObjectModel> = 
  this.observableSource.asObservable();


setObservableValue(data: YourObjectModel) {
  this.observableSource.next(data);
}

getObservableData() {
  return this.subscribableObservable;
}



In your COMPONENT:

this.service.getObservableData().subscribe(latestObservableData => {
  this.schoolList = latestObservableData;
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to choose a key from a discriminated union type?

I have a discriminated union with different types type MyDUnion = { type: "anonymous"; name: string } | { type: "google"; idToken: string }; I am trying to directly access the 'name' key from the discriminator union, like thi ...

What is the process for adjusting the color of axes in vue-chartjs?

Seeking help on how to adjust the color of the axis in my graph. Has anyone encountered a similar issue before? The chart I'm working with resembles the one shown in the image. Not sure if this issue is related to it being a time graph. Below is the V ...

obtainServerSideProps query parameter

Hey there, I'm trying to use NextJS and its getServerSideProps function to send an API Request, but I'm having trouble passing my ID Query Parameter along. The URL for my API is: http://localhost:3001/product/${id} Below is my code: const rout ...

Creating a ref with Typescript and styled-components: A comprehensive guide

Trying to include a ref into a React component looks like this: const Dashboard: React.FC = () => { const [headerHeight, setHeaderHeight] = useState(0); const headerRef = React.createRef<HTMLInputElement>(); useEffect(() => { // @ts ...

Angular input form is throwing an error because it is unable to retrieve the property 'name' of an undefined value

I've been working on creating a simple Angular component following a tutorial I found. The component fetches data from an angular-in-memory-web-api using a service called UserService. I have also added an input form for creating new users. The issue ...

Is there a way to locate a parent class starting from a child class, and subsequently track down another child class from the parent?

I am facing a challenge with multiple tags structured like this: <div class="A"> <div class="B1">...</div> <div class="C1">Hello World!</div> <div class="C2">World Hell ...

Sending various data from dialog box in Angular 8

I have implemented a Material Design dialog using Angular. The initial example had only one field connected to a single parameter in the parent view. I am now trying to create a more complex dialog that collects multiple parameters and sends them back to t ...

The Service Worker seems to be neglecting to serve the sub-pages at

I've successfully implemented a service worker on my website. The home page loads correctly from the Service Worker cache, and when I visit previously viewed 'posts' while online in Chrome, they load and show as 'from ServiceWorker&apos ...

Experiencing a problem in AngularJS 2 after including 'routing' in the imports section of app.module.ts

An issue arises when I include 'routing' in the imports section of app.module.ts app/app.routing.ts(18,23): error TS2304: Cannot find name 'ModuleWithProvider'. [0] app/app.routing.ts(18,65): error TS2304: Cannot find name 'AppRou ...

What are the steps involved in incorporating a REST API on the client side?

Hey there! Today I'm working with a simple Node.js express code that functions as a REST API. It works perfectly when I use Postman to send requests with the GET method, as shown in the code below. However, when I try to implement it on the client sid ...

The functionality of Material UI tooltip is not functioning properly when accessed on mobile devices

Attempting to transform Tooltip into a controlled component that relies on the onClick event. While this setup works well on mobile and web, it loses its original functionality of showing the Tooltip on hover. Is there a way to make the Tooltip function ...

ng-bind-html is having trouble parsing the HTML correctly and binding it

Here is the code for my controller: myApp.controller('actionEditController', ['$scope', '$stateParams', '$sce',function ($scope, $stateParams, $sce) { $scope.table="<p>OOPSY</p>"; $sc ...

Having trouble getting datatables.net to function properly with JavaScript

I've been experimenting with datatables from http://datatables.net/ Attempting to make it work using javascript, but I'm facing issues. Even when following the example provided on the website, it still shows a blank page. Does anyone have any su ...

Step-by-step guide on setting fa fa-check as the background image for the selected field in Angular 4 with ng-select

I am implementing an ng-select field and would like to display a check mark for the selected option in the dropdown list using fontawesome check. However, I am unsure of how to achieve this. Can anyone provide guidance? HTML: <ng-select class="box" p ...

Node.js project that was once functional is now encountering issues with the error message: "Error: Route.post() requires a callback function but received [object Undefined]."

When it comes to asking questions, I typically provide a lot more detail and use specific wording in my titles. However, I'm currently facing an issue that has left me stumped on where to find the solution. Recently, I delved into learning Node JS an ...

Creating a custom autocomplete search using Angular's pipes and input

Trying to implement an autocomplete input feature for any field value, I decided to create a custom pipe for this purpose. One challenge I'm facing is how to connect the component displaying my JSON data with the component housing the autocomplete in ...

Challenges with Angular directive scopes

My current task involves taking an existing template and Angularizing it. I am dealing with 3 directives: a card, a card-header, and a card-body: <card> <card-header title="My Card"> <input type="text" ng-model="userSearch" /&g ...

What is the reasoning behind storing type definitions in the @types namespace within npm?

Have you ever wondered why type definitions in npm are stored under the @types namespace which isn't directly linked to a specific organization, user, or library? Wouldn't it make more sense for npm libraries to have their types located under @[o ...

Saving data in multiple collections using MongoDB and Node.js: A comprehensive guide

In a recent project of mine, I have implemented a combination of nodeJS and mongodb. My main goal is to store data in multiple collections using just one save button. Below is the code snippet that I am currently working with: var lastInsertId; loginDat ...

Issues with incorrect source path in Typescript, Gulp, and Sourcemaps configuration

In my nodejs app, the folder structure is as follows: project |-- src/ | |-- controllers/ | | |`-- authorize-controller.ts | |`-- index.ts |--dist/ | |--controllers/ | | |`-- authorize-controller.js | | |`-- authorize-controller.js.map | ...