Sign up for various services one after the other

In my project, I have the need to perform 2 API calls in sequence. The second call does not depend on the first one, and both calls update the database. However, when using the code below, the update for the second call is happening multiple times, leading to multiple updates on the same record which should be avoided. Any assistance on this matter would be greatly appreciated.

updateUserCommentsObservable(): Observable<any> {
  if (!this.userComments) {
    return EMPTY;
  }

  const source = this.arrayGroupBy<TrailerComparisonUserComment>(
    this.userComments, 
    comment => comment.trailerComparisonId);
  return from(Object.keys(source)).pipe(
    mergeMap(x => this.trailerComparisonService.updateUserComments(
      x, source[x])
    )
  );
}


this.updateUserCommentsObservable().pipe(
  flatMap(() => from(this.trailerComparisons).pipe(
    mergeMap(trailerComparison => 
      this.trailerComparisonService.saveReviewComplete(
        trailerComparison.trailerComparisonId))
    )
  )
).subscribe(() => {                   
  this.userComments = [];
  this.disableStage1Review = true;
  let snackBarRef = this.snackBar.open('Well done! Stage1 Review Complete has been successfully saved.', 'Dismiss');                   
}, error => {                   
  console.log("Error", error);
  let snackBarRef = this.snackBar.open('Error! ' + error.error.message, 'Dismiss');
});

Answer №1

If you need to sequentially run multiple observables, you can utilize the concat function.

concat(
  obs1$,
  obs2$
).subscribe(result => {
  console.log(result);
});

In case each observable produces one result and completes (like an http request), the subscribe method will receive two values - first from obs1$ and then from obs2$.

To wait until all results are available, you can use the toArray function.

concat(
  obs1$,
  obs2$
).pipe(
  toArray()
).subscribe(result => {
  console.log(result);
});

Now, the subscribe callback will receive an array containing the results of both obs1$ and obs2$.

If your scenario involves an initial observable followed by an array of observables that need to be executed sequentially, you can create an array of observables beforehand and pass them into the concat function.

const trailerComparisons$ = this.trailerComparisons.map(c => 
  this.trailerComparisonService.saveReviewComplete(c.trailerComparisonId)
);

concat(
  this.updateUserCommentsObservable(),
  ...trailerComparisons$
).pipe(
  toArray()
).subscribe(/* handle subscription */)

Check out the DEMO: https://stackblitz.com/edit/angular-jldrrh

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

The operation failed because the property 'dasherize' is inaccessible on an undefined object

While attempting to execute the following command: ng generate component <component-name> An error occurred saying: Error: Cannot read property 'dasherize' of undefined Cannot read property 'dasherize' of undefined The confi ...

How can the `ng new --collection` command be utilized in Angular?

Can you explain the purpose of using the ng new --collection command in Angular? And can you provide instructions on how to use it in the command prompt? If you have any knowledge about this, please share with me. ...

Getting rid of parameters in HttpParams in Angular 4.3

I am working with a HttpParams object that looks like this: private filter: HttpParams = new HttpParams(); [...] this.filter = this.filter.append('page','1'); this.filter = this.filter.append('pageSize','50'); this. ...

What are the steps to successfully upload a nestjs application (using typescript) onto the heroku

After creating a nestjs app, I am now seeking the most efficient way to deploy it on Heroku for production environment. Upon attempting to deploy the code generated by nest-cli as-is, I received the following logs from Heroku: 2018-12-28T08:37:23.881261+ ...

Creating custom disabled button styles using TailwindUI in a NextJS application

I had a NextJS application that utilized Atomic CSS and featured a button which becomes disabled if a form is left unfilled: <Button className="primary" onClick={handleCreateCommunity} disabled={!phone || !communi ...

The functionality of expandable rows on the material table seems to be malfunctioning once sorting is

After implementing expandable rows and sorting in my table based on the samples provided in Angular Material Table, I encountered an issue. When I try to expand a row after sorting the table, the first click appears to have no effect. The second click brie ...

Issue encountered when attempting to run the Angular 7 application using Node Js LTS version 16.13.2

I have set up an Angular 7 app using the following docker file with Node.js version 16.13.2 LTS FROM node:16.13.2 ENV context "" RUN mkdir -p /usr/src/ WORKDIR /usr/src/ COPY . /usr/src/ RUN npm install ENV context "" EXPOSE 3000 CMD [ ...

What is the best way to find the clinic that matches the chosen province?

Whenever I try to choose a province from the dropdown menu in order to view clinics located within that province, an error 'TypeError: termSearch.toLowerCase is not a function' pops up. This part of the code seems confusing to me and any kind of ...

What is the best approach for implementing line coverage for object literal in Typescript Mocha unit-tests?

Lead: I am a newcomer to using typescript and writing unit tests with Mocha and Chai. Question: Can anyone provide tips on achieving 100% line coverage in unit tests for an object literal that isn't within a class? I want to avoid going static if pos ...

Angular Migration - Unable to locate a suitable version

I need to upgrade my application from Angular 10 to Angular 11. However, during the migration process, I encountered the following error: npm ERR! code ETARGET npm ERR! notarget No matching version found for @ruf/<a href="/cdn-cgi/l/email-protection" cl ...

How can we enhance intellisense to recognize instance members of an interface when using dynamic indices?

In the midst of developing an angular project, I am currently utilizing an interface to specify a configuration for a module. The design of the interface revolves around mapping names to objects and is relatively straightforward: export interface NamedRou ...

Issue with Angular trackBy not functioning properly within a nested *ngFor loop

My component is similar to the following <div class="users-list" *ngIf="datasetPermission !== undefined"> <div *ngFor="let userpermission of datasetPermission; trackBy : trackByFn"> <span *ngFor="let user of userpermission.users"& ...

angular material drag and drop triggers a callback once the css transition has completed

I have successfully implemented a list of elements that can be dragged and dropped using Angular Material's drag and drop feature, similar to the tutorial available at this link. In my implementation, I have a "drop(event)" function that not only mov ...

Error: The code encounters a SyntaxError due to an unexpected token '?' in iOS 14

Currently in the process of developing a Headless Shopify project using this starter: https://github.com/vercel/commerce. While testing the demo environment, I encountered some bugs that seem to be specific to iOS 14 or newer. The primary issue stems from ...

Exploring Angular 6 CLI Workspaces: A Guide to Creating Libraries for Exporting Services

Introduction: In Angular CLI 6, a significant feature called workspaces was introduced. A workspace has the ability to house multiple projects within it. All configurations for the workspace and its projects are stored in an 'angular.json' fi ...

Encountered an error with create-react-app and MaterialUI: Invalid hook call issue

I am encountering an issue while trying to set up Create-react-app with Material UI. The error message I receive pertains to Hooks. Could there be something else that I am missing? This is the specific error message being displayed: Error: Invalid hook ...

Issues encountered with sending post requests to a yii2 application when using Angular4

After implementing the following code: this.http.post('http://l.example/angular/create/', {name: 'test'}).subscribe( (response) => console.log(response), (error) => console.log(error) ); I encountered an error on ...

Issues have been encountered with Angular 5 when trying to make required form fields work properly

Just created my first Angular app using Angular 5! Currently following the documentation at: https://angular.io/guide/form-validation. Below is the form I have set up: <form class="form-container"> <mat-form-field> <input matInput pl ...

Troubleshooting: Why is my ng serve command in Angular 5 not

Whenever I try to run ng serve, an error pops up ng : The term 'ng' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is ...

A guide on harnessing the power of forEach in Ionic 4

I'm currently in the process of upgrading my Ionic v1 app to Ionic 4. Within my app, there is a forEach loop that needs to be adjusted for Ionic 4 compatibility. Here is the code snippet from Ionic v1: angular.forEach(this.selectedQuestion.answers, ...