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

Saving a local JSON file in Angular 5 using Typescript

I am currently working on developing a local app for personal use, and I want to store all data locally in JSON format. I have created a Posts Interface and an array with the following data structure: this.p = [{ posts:{ id: 'hey man&ap ...

Specializing in narrowing types with two generic parameters

In my current project, I am working on a function that takes two generic parameters: "index" which is a string and "language" which can also be any string. The goal of the function is to validate if the given language is supported and then return a formatt ...

Error in Firebase Emulator: The refFromUrl() function requires a complete and valid URL to run properly

Could it be that refFromURL() is not functioning properly when used locally? function deleteImage(imageUrl: string) { let urlRef = firebase.storage().refFromURL(imageUrl) return urlRef.delete().catch((error) => console.error(error)) } Upon ...

Angular Material datetime picker with an option for transparent background

After upgrading my angular from version 15 to 16, I encountered a strange issue with the material date time picker. The GUI part of the picker appeared half transparent as shown in this image: Has anyone else faced this kind of problem with the material d ...

Transfer my testing utilities from React Router version 5 to version 6

I am currently transitioning my project to React V6 router and encountering an issue with my test utility function. Every time I run the test, all my expectations fail because jest cannot locate the object. Has anyone faced this error during a similar migr ...

Using Directives inside a Standalone Component in Angular: A Step-by-Step Guide

As I work on integrating a directive that is not standalone into a Standalone component, I encountered an error. The specific error message can be viewed here. Even after including the directive in the component's import array as shown here, the issu ...

Angular 2: Accessing the parent component from the output

I am a beginner in Angular 2 and I've been exploring ways to access the value of an attribute from a parent component using the @Output feature. Below is the code snippet: ParentPage.ts export class ParentPage { name: string; constructor(){ ...

NG8003 error: ExportAs 'ngForm' directive not found in the system

I encountered an issue with my first Angular 11 project: No directive found with exportAs 'ngForm'. Despite importing FormsModule and ReactiveFormsModule in app.module.ts, the error persists. Here is the code snippet: This is from product.compon ...

Using Mat-Error for Two Way Binding leads to frequent triggering of ngModelChange事件

I am working with a mat input field that has two-way data binding using ngModel, and I want to add validation using mat-error and formControl. <mat-form-field [formGroup]="myForm"> <input matInput formControlName="myFormName" autocomplete="off" ...

Excluding files in Angular by adding them to the .gitignore list

Interested in mastering the integration of Twilio with your Angular app? The first step is to configure your Twilio credentials and make sure to add that file to the .gitignore. However, upon reviewing this example Angular-Twilio project on GitHub, I notic ...

Enhance your PrimeNG p-calendar by customizing the background-color of the dates

Hello, I am currently attempting to customize the appearance of the p-calendar, but I am struggling with changing the color of the displayed dates. Can anyone provide assistance? Thank you in advance. Below is my template: <div class="p-field p-co ...

Errors encountered during the Angular project build

I need help figuring out what's happening. I keep getting the same error while trying to build my project. I've already attempted deleting typings, angular directory, and performing typings install but nothing seems to be working. All the necess ...

How to identify alterations in user input within Angular?

I need assistance with my search input functionality. I want to ensure that the this.searchProperties.emit is only triggered when the user interacts with the input field by touching it or making an input. The current issue is that the emit function gets ca ...

Distribute the capabilities of the class

Is there a way to transfer the functionalities of a class into another object? Let's consider this example: class FooBar { private service: MyService; constructor(svc: MyService) { this.service = svc; } public foo(): string { ...

Identifying browser compatibility for date input type with Angular 2 and above

Is there a reliable method to check if the browser supports <input type="date"> in Angular2+? I came across a suggestion on https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/date where they recommend creating the input element and chec ...

Error: Unable to locate the specified Typescript function

For the source code, please visit https://github.com/zevrant/screeps I am encountering an issue with my implementation of interfaces in TypeScript. When trying to call the implemented interface, I am getting the following error: "TypeError: spawn.memory.t ...

Tips for effectively utilizing TypeORM transactions

I'm encountering an issue with transactions in TypeORM. Here's a snippet of the code causing me trouble: const someFunction = async () => { try { await this.entityManager.transaction(async (manager) => { //some opera ...

How to Utilize Knockout's BindingHandler to Integrate JQuery.Datatables Select Feature?

I've developed a custom KO bindingHandler (view it here) to assist in updating the DataTable. The documentation for JQuery.DataTable.Select regarding how to access data requires a handle. You can see the details here. var table = $('#myTable&a ...

Struggling to share information between components using RxJS Subject or a shared service?

I've been attempting to transfer data between components using a Subject and a shared service, but I'm encountering issues with it not functioning as expected. It's worth mentioning that I included the service at the module level rather tha ...

There was an error in Angular at core.js:6150 stating that the object is not iterable due to a

I am facing an issue in displaying the First Name of a user in an HTML file getFirstName(id: any){ this.users = this.afs.collection('users', ref => ref.where("uid", "==", id)).valueChanges(); this.users.subscribe(users => { ...