What is the process for waiting on RxJS data and how should it be retrieved?

I am faced with a situation where I need to create a user through a function, but before proceeding with the creation process, I have to verify whether another user with the same userName is already present in the session:

public createUser(form: FormGroup, sessionCode?: string): void {
  if (sessionCode && this.checkForDuplicateUserInSession(form, sessionCode)) return;

  this.apollo.mutate<CreateUser>({
    mutation: CREATE_USER,
    variables: {
      name: form.controls['user'].get('userName')?.value,
    },
  }).subscribe(
    ...
  );
}

private checkForDuplicateUserInSession(form: FormGroup, sessionCode?: string): void {
  this.apollo.query<GetSession>({
    query: GET_SESSION,
    variables: {
      code: sessionCode
    }
  }).subscribe({
    next: ({data}) => {
      return data.getSession.players.some((player) => player.name === form.controls['user'].get('userName')?.value);
    }
  });
}

The functionality of checkForDuplicateUserInSession() is accurate in determining the presence of any duplicate users, however, integrating it within the createUser() function seems challenging.

Should I establish an observable like userIsDuplicate$ and feed the outcome of some() into that before subscribing? Is there perhaps an alternative approach that I am overlooking?

Answer №1

Utilize the lastValueFrom function within the method checkForDuplicateUserInSession to convert an Observable into a Promise (documentation here). Then, implement async/await for the createUser method.

Illustration:

public async createUser(form: FormGroup, sessionCode?: string): void {
    if (sessionCode && await this.checkForDuplicateUserInSession(form, sessionCode)) return;
    
    this.apollo.mutate<CreateUser>({
        mutation: CREATE_USER,
        variables: {
            name: form.controls['user'].get('userName')?.value,
        },
    }).subscribe(
          ...
    );
}
    
private checkForDuplicateUserInSession(form: FormGroup, sessionCode?: string): void {
    return lastValueFrom(this.apollo.query<GetSession>({
        query: GET_SESSION,
        variables: {
            code: sessionCode
        }
    }).subscribe({
        next: ({data}) => {
            return data.getSession.players.some((player) => player.name === form.controls['user'].get('userName')?.value);
        }
    }));
}

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

Evolving fashion trends

I'm looking to dynamically change the style of my HTML element based on screen size, similar to this example: <p [ngStyle]="{'color': isMobile() ? 'red' : 'blue'}">Lorem Ipsum</p> The code above triggers a m ...

Is it possible to conceal a component from all other active components?

One key element in the application is the <app-tabs-components> component. This component retrieves data from a service. The service contains a variable called show: boolean, which controls whether the component is displayed or hidden on the page. ...

Issue with Angular Datatable: Table data is only refreshed and updated after manually refreshing the page or performing a new search query

Having trouble updating Angular Datatable after selecting different data? The API response is coming in but the table data is not being updated. Can anyone suggest how to properly destroy and reinitialize the table for the next click? Below is a snippet ...

Tips for building an Angular app with Vite hosting

Looking to build an Angular application using Vite with simple routing, limited features, and no test files while running on port 5000. I have scoured the internet but haven't found a solution yet. ...

`Angular 6 and the expiration of Jwt tokens`

I am currently developing an angular application that utilizes jwt for authenticating database calls. However, I encountered a problem where, when the token expires on the server, the app starts displaying blank pages instead of the expected data. This hap ...

Creating layers of object declarations

Looking for assistance on the code snippet below. type Item = { id: number; size: number; } type Example = { name: string; items: [ Item ]; } var obj: Example = { name: "test", items: [ { i ...

Troubleshooting Electron Angular Application Connectivity Issues with API

While developing my ionic/angular app as an electron app, I encountered a problem when running it. After loading, I received the error message shown below: Refused to connect to 'https://xxxxxxxxxx.com/whpacking/v1/getlocations' because it violat ...

Transferring functionality from a child component to a parent component

I have a Base Component called ListComponent and a ParentComponent named Businesses2ListComponent. The concept is to have multiple types of Lists with tables that all stem from the ListComponent. This requires passing the correct service accordingly. In t ...

Issues arise when compiling Angular 9 with Ivy in a Docker environment

Looking to create a new Angular 9 project using a custom image based on the official node image. I want to cache the package build without caching the Angular source build. Check out my Dockerfile below: FROM node COPY package.json /mnt/ RUN c ...

Obtain a reference to a class using a method decorator

My goal is to implement the following syntax: @Controller('/user') class UserController { @Action('/') get() { } } Now in the definition of decorators: function Controller (options) { return function(target: any) { let id ...

Guide to Rolling a Set of 5 Dice

I am looking to develop a game involving 5 dice. I have already created a function to roll one die using a random method, but I am unsure how to extend this functionality to the remaining four dice without having to create a separate method for each one. ...

Issues with implementing Dark mode in TailwindCSS with Nuxt.js

After spending a couple of days on this, I'm still struggling to get the dark mode working with Tailwind CSS in Nuxt.js. It seems like there might be an issue with the CSS setup rather than the TypeScript side, especially since I have a toggle that sw ...

Which ngTagsInput version is recommended for Angular instead of AngularJs?

After discovering the ngTagsInput framework on this site, I found it to be a very comprehensive library. However, for Angular 8 users like myself, I came across the ngx-chips framework on this page. While ngx-chips seems to work, I noticed that it lacks s ...

What is the reason why modifying a nested array within an object does not cause the child component to re-render?

Within my React app, there is a page that displays a list of item cards, each being a separate component. On each item card, there is a table generated from the nested array objects of the item. However, when I add an element to the nested array within an ...

Angular Service Fails to Execute Upon Initial Loading

In my current project, I am utilizing Angular 9.0.7 with a Node.js (Express) backend and an Angular frontend. The issue I'm facing is that the service function responsible for fetching data from the backend is not being invoked on the initial page lo ...

Typescript is failing to infer the definition of an object, even after conducting a thorough check

I am encountering an issue with the code structure below: interface Data { isAvailable: boolean; } const foo = (data: Data | undefined, error: boolean) => { const hasError = error || !data; if (!hasError) { if (data.isAvailable) // do so ...

Utilizing Angular PWAs: Leveraging Service Workers for Scheduled Tasks and Asynchronous Operations in Web Applications

Exploring angular service workers and seeking specific functionalities: Interested in creating a separate thread to handle periodic purging of an indexedDb, along with notifying active tabs once done. Desire for a separate service/job to manage background ...

Why can't we import Angular 4 as a library similar to AngularJS?

Why was AngularJS introduced as a script to import in an HTML page? However, in the newer version Angular 4, we need to use a web server to launch the application? Is it because AngularJS is not considered a framework but Angular 4 is? Thank you. ...

Encountering issues while retrieving date data from Firebase in Angular 6

this.qS = this.afDatabase.list('path', ref => { return ref.limitToLast(1000); }).snapshotChanges().map(changes => { return changes.map(c => ({ key1: c.payload.key,value1:c.payload.val() })); }); this.qS.subscribe(values =&g ...

What is the method to send numerous forms with a single click on Angular Material Stepper?

My user interface presents a unique scenario that is different from the question posed. To address the issue of submitting forms within a stepper in Angular 4 Material, I have set up a situation where I need to create a single stepper containing multiple f ...