Search code examples
angularrefreshsubscribe

Angular 5 - implementing finally on subscribe


I am writing an app with Angular 5.

I am working on using the ion-refresher to refresh the page and I want to cancel the spinner if there is either an error or a success back so essentially a finally block.

I need the refresh to stop spinning and go back to the default position in any outcome (success or error).

How can I achieve this with my code? This is what I have tried and I get an error:

html

<ion-content>
    <ion-refresher slot="fixed" (ionRefresh)="refresh($event)"></ion-refresher>
        <div *ngIf="data">
         {{ data }}
        </div>
</ion-content>

component

export class UserInfoComponent implements OnInit {

    data: any;

    constructor(private userInfoService: UserInfoService) {}

    ngOnInit() {

        this.userInfoService
            .getEmployeeInfo()
            .subscribe((response) => {
              this.data = response;
            });
    }

    refresh(event) {

        this.userInfoService
            .getEmployeeInfo()
            //.pipe(
              //.finally(() => event.complete())
            //)
            .subscribe((response) => {
              this.data = response;
              event.complete(); //this works but what if there was an error
            })
            //.finally(() => event.complete());
            //Property 'finally' does not exist on type 'Subscription'.
    }

}

Solution

  • When using subscribe:

    someObservable.subscribe(
      (response) => {
          // do something when data is received
          console.log(response);
      }),
      (err) => {
          // do something on error
          console.error(err)
      },
      () => {
          // do something when operation successfully complete
          console.log('success!);
    });