Home > Software design >  RxJS Subscription and code execution in it
RxJS Subscription and code execution in it

Time:05-24

In many projects, I see this kind of subscription code:

isLoading: boolean; // the variable initializes, for instance, the display of the loader

The next step is to load the content of the page:

this.loadSomething(): void {
  this.isLoading = true;
  this.someService.getMethod(data)
  .subscribe(response => {
      if (response) {
      ...do something
      }
    },
    (errors: HttpErrorResponse) => {
      ...do something
    },
    () => {
      this.isLoading = false;
    }
  );
};

As far as I know, the third .complete() subscription argument will not be executed in case of an error. Thus, if we receive an error from the server, this.isLoading = false; will not be executed and we will not see the data page, and we will see an infinite loader.

In my code I always write like this:

this.loadSomething(): void {
  this.isLoading = true;
  this.someService.getMethod(data)
  .subscribe(response => {
      this.isLoading = false;
      if (response) {
      ...do something
      }
    },
    (errors: HttpErrorResponse) => {
      this.isLoading = false;
      ...do something
    }
  );
};

..that is, without using the .complete() block

I can't figure out why it's written this way or am I missing something? How do you subscribe and how do you do it correctly?

CodePudding user response:

You can use finalize operator to handle loading disablement, it'll run after upon complete or error

this.someService.getMethod(data).
pipe(finalize(()=>this.loading=false))
.subscribe()

CodePudding user response:

this.someService.getMethod(data).subscribe(this.observer)


detectChanges() {
  this.loading = false;
  this.ref.detectChanges(); // if you are using OnPush strategy
}

 observer = {
  next: (data) => {
    // do stuff
    console.log(data);
    this.detectChanges()
  },
  error: (error) => {
     // do stuff
     // throw httpResponseError or treat error here
     console.log(error)
     this.detectChanges()
  },
  complete: () => {
     console.log("data has been loaded")
     this.detectChanges()
  }
}
  • Related