Retrigger http GET call in Angular

Let’s implement a http get call that can be “refreshed”, or recalled again so it fetches the data again. You might do some updates through SQL but because you already loaded the data, you need to get it again. This can be achieved with rxjs method switchMapTo.

Have your variable of the Observable type, I’ll call it myData$ with the type of Object.

All of this is inside a service I called myService.

Let’s first declare a property like this inside our myService class:

myData$: Observable<Object>;

Then another property we name event$ of the type BehaviorSubject with the default value of true.

  event$ = new BehaviorSubject(true);

Then inside my constructor I’ll declare myData$ to be equal to the switchMapTo like this:

    this.myData$ = this.event$.pipe(
  getMyData(): Observable<Object> {
    return this._http.get(environment.APIPath + "/getData", {
      //headers: .. etc

Then we have our main getMyData() function which gets our through a http get call (using Angular’s HttpClient). Replace the URL parameter to whatever you are getting here, I myself have a URL of http://localhost/api/getData (the environment variable is http://localhost/api and the last part is the API function URL /getData). This will be called anytime event$ gets an incoming value. Let’s create the refresh/refetch method like this for event$:

  refetchData() {

Now we can call the refetchData() and we wil push in the boolean true value so that the BehaviorSubject is triggered and thus getMyData gets called again and our myData$ now contains the latest http GET call result. All left to do is to subscribe to it (in this case we save it to a property we call myData)!

 this.myService.myData$.subscribe((s:any) => {
        this.myData = s;
0 0 votes
Article rating
Notify of

Inline Feedbacks
View all comments