MarkeZ
MarkeZ

Reputation: 157

Multiple call to API

How Can I make one function to call api one by one? I got something like this

  getCheckInFiles(res) {
    this.loading = true;

    this.checkFiles.getUploadedCheckInFiles(res).pipe(
      finalize(() => this.loading = false)
    ).subscribe(data => {
      this.isUploadedCheckIn = data;
      if (this.isUploadedCheckIn === true) {
        this.isUploadedCheckIn = "OK";
      } else if (this.isUploadedCheckIn === false) {
        this.isUploadedCheckIn = "None";
      }
    });
    this.checkFiles.getUploadedCheckOutFiles(res).pipe(
      finalize(() => this.loading = false)
    ).subscribe(data => {
      this.isUploadedCheckOut = data;
      if (this.isUploadedCheckOut === true) {
        this.isUploadedCheckOut = "OK";
      } else if (this.isUploadedCheckOut === false) {
        this.isUploadedCheckOut = "None";
      }
    });
    this.checkFiles.getUploadedStayFiles(res).subscribe(data => {
      this.isUploadedStay = data;
      if (this.isUploadedStay === true) {
        this.isUploadedStay = "OK";
      } else if (this.isUploadedStay === false) {
        this.isUploadedStay = "None";
      }
    });
  }

It checking if file is avalible in directory. It works fine but I got 5 functions like this.

And I also want to add loader if function getCheckInFIles is done - I did it only for first call but how can I catch finish of all calls?

Response is true or false

How should I did it in right way?

Upvotes: 0

Views: 97

Answers (1)

Some random IT boy
Some random IT boy

Reputation: 8457

You can use the combineLatest rxjs operator in the following manner:

const operations = [ 
  this.checkFiles.getUploadedCheckInFiles(res),
  this.checkFiles.getUploadedCheckOutFiles(res),
  this.checkFiles.getUploadedStayFiles(res),
  // Add more if you want; assuming they all return the same response
]


combineLatest(operations)
  .pipe(
    finalize(() => (this.isLoading = false))
  )
  .subscribe(([uploadedCheckIn, uploadedCheckOut, uploadedStay]) => {
    this.isUploadedCheckIn = uploadedCheckIn ? 'OK' : 'Not ok'
    this.isUploadedCheckOut = uploadedCheckOut ? 'OK' : 'Not ok'
    // Etc.
  })

Upvotes: 1

Related Questions