Hold off until the operation finishes executing and then deliver Angular 6

Is there a way to delay the subscribe function until my logic is complete and the transform method has updated the keys object?

transform(value: any, args:string) : any {
    let keys = [];

    this.http.get('src/app/enum-data/enum.json').subscribe(data => {

      this.List = data;
      // Implement logic here (comparing data vs value)
      for (var enumMember in value) {
        if (!isNaN(parseInt(enumMember, 10))) {
          keys.push({key: enumMember, value: value[enumMember]});
        } 
      }
    },
      err => {
        console.log(err);
      });

    return keys;

  }

HTML:

  <select>
          <option *ngFor="let item of gendersEnum | keys: 'gender'" [value]="item.key">{{item.value}}</option>
  </select>

This involves a custom pipe module. I attempted to return keys within the subscribe, but encountered the same issue.

Answer №1

Instead of subscribing your Observable here, you should map the response using RxJs operators and only subscribe when calling transform(...).

transform(value: any, args: string): Observable<any> {
        return this.http.get('src/app/enum-data/enum.json').pipe(
            map(data => {
                let keys = [];
                // Implement logic here (data vs value)
                for (const enumMember in value) {
                    if (!isNaN(parseInt(enumMember, 10))) {
                        keys.push({key: enumMember, value: value[enumMember]});
                    }
                }
                return keys;
            })
        );
    }

A more efficient approach is to utilize the async pipe to allow Angular to manage the subscription and unsubscription of your observable:

<select>
          <option *ngFor="let item of gendersEnum | keys: 'gender' | async" [value]="item.key">{{item.value}}</option>
  </select>

Answer №2

Implemented some alterations in the technique.

transformData(value: any, args:string) : Observable<any>{
  return this.http.get('src/app/enum-data/enum.json').map(data => {
     let keys = [];
      this.List = data;
      // Custom logic here (data vs value)
      for (var enumMember in value) {
        if (!isNaN(parseInt(enumMember, 10))) {
          keys.push({key: enumMember, value: value[enumMember]});
        } 
      }
      return keys;
    },
      err => {
        console.log(err);
      });

  }
Now you can implement Your modified method by subscribing.

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

Manipulating Angular and Typescript to utilize the method's parameter value as a JavaScript object's value

I am currently working with Ionic, Angular, and Typescript, attempting to dynamically set the value of a location based on the parameter passed from a method. Here is the relevant code snippet: async fileWrite(location) { try { const result = a ...

What is the best way to loop through an array that contains a custom data type

When I declared the type: export interface Type{ id: number; name: string; } I attempted to iterate over an array of this type: for(var t of types) // types = Type[] { console.log(t.id); } However, I encountered the following error message: ...

The error `TypeError: Unable to access properties of an undefined value (reading 'authService')` occurred

I'm attempting to check if a user is already stored in local storage before fetching it from the database: async getQuestion(id: string): Promise<Question> { let res: Question await this.db.collection("questions").doc(i ...

Typescript: Implementing the 'types' property in a function returned from React.forwardRef

I'm exploring the option of adding extra properties to the return type of React's forwardRef function. Specifically, I want to include the types property. Although my current implementation is functional, given my limited experience with TypeScri ...

Error message: "Unable to locate HTML container when trying to create a child element in am

Whenever I navigate away from this page and then come back, the chart does not load. Instead, it displays an error message saying html container not found at createChild However, if I refresh the page, the chart will appear again. The issue seems to be i ...

Give it a little time before uploading a widget onto the page

As a newcomer to programming, I recently came across this code from an open source project. I am in the process of loading a widget onto a website. Instead of having the widget load instantly, I would like it to wait 10 seconds before displaying. Below i ...

Passing Parent Method to Child Component in React Native

I'm experiencing an issue trying to pass a method from my parent component to a child component. Although I believe my code is correct, I keep getting the error message undefined is not an object(evaluating '_this2.props.updateData'). Despit ...

What is the method to insert a new <input> element after the last input field has been filled in

I recently started working on a form using StackBlitz, but I've hit a roadblock and need some guidance on how to proceed. My goal is to achieve a similar effect like the one shown in this gif: https://i.stack.imgur.com/76nsY.gif and I'd like to ...

Every time I attempt to make an HTTP request, I encounter a cross-origin error

When I make requests from the browser, they are valid. However, when using the Angular 9 app, I receive a 401 error. Below is the header from Chrome: Request URL: http://localhost:1234/api/Common/GetMy_List Request Method: GET Status Code: 401 Referre ...

Sending an onclick event to a child class through React and TypeScript

I'm currently working through the Facebook React tutorial with Typescript for the first time. I need to pass an onClick event to the 'Square' component, which is implemented using Typescript and interfaces for state and props. How can I mod ...

Implementing OpenID Connect with Angular Single Page Application and Asp.Net Core 3.1 Backend

I am embarking on a project to develop a cutting-edge (Angular) Single Page Application with a robust (Asp.Net Core) back-end, all while prioritizing security best practices. Here is the blueprint for my plan: The SPA showcases a Login button When the use ...

Ionic app: refresher functionality works in browser but not on iOS home screen app

I am currently developing a Progressive Web App (PWA) using Ionic, and I have implemented an ion-refresher in the app: <ion-content> <ion-refresher slot="fixed" (ionRefresh)="refresh()"> <ion-refresher-content pullingIcon="lines">& ...

Using TypeORM: Implementing a @JoinTable with three columns

Seeking assistance with TypeORM and the @JoinTable and @RelationId Decorators. Any help answering my question, providing a hint, or ideally solving my issue would be greatly appreciated. I am utilizing NestJS with TypeORM to create a private API for shari ...

Creating a realistic typewriter effect by incorporating Code Block as the input

I am looking to add a special touch to my website by showcasing a code segment with the Typewriter effect. I want this code block not only displayed but also "typed" out when the page loads. Unfortunately, I have been unable to find a suitable solution s ...

angular index.html code displayed

I successfully deployed an Angular app on a server in the past without any issues. The Angular version is 6.1.1, Angular CLI version is 6.2.9, npm version is 6.13.4, and node version is 10.18.0 for both local and server environments. The server is running ...

Troubleshooting the "invalid configuration" error when using Angular CLI to create a new app

While attempting to develop a new application with angular CLI, I continuously encounter the "invalid configuration" error. This same error pops up when executing the ng --version command. $ ng new angular_organicstore An invalid configuration file was fo ...

Is there a way to dynamically adjust the size of mat dialog content to match the size of the mat dialog in

I have adjusted the size of my mat dialog, but the content is still stuck at the original size. To illustrate, here are some images: https://i.stack.imgur.com/2lLV2.jpg After researching, I found that it can be resized using CSS. I attempted the followin ...

Testing Slack's Web API with Jest for mock purposes

Currently, I am working with two files. One file is where I set up a slack web API client to post a message and test it with a mocked value: main.ts: import { WebClient } from '@slack/web-api'; const slack = new WebClient(process.env.SLACK_API_K ...

Avoid selecting primary key column in TypeORM查询

Is it possible to exclude primary key columns from being selected in TypeORM? I've tried using the select false option, but it doesn't seem to work for these specific columns. Could it be because they are essential for identifying the entity or b ...

The 'mat-table' component is triggering an error indicating that the 'dataSource' attribute is unrecognized in the table

Recently, I have been diving into the world of Material Library for Angular. Working with Angular version 15.0.1 and Material version 15.0.1, I decided to include a mat-table in my form (schedule.allocator.component.html): https://i.stack.imgur.com/c7bsO. ...