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

Typescript: Verifying the type of an interface

In my code, I have a function called getUniqueId that can handle two different types of interfaces: ReadOnlyInfo and EditInfo. Depending on the type passed to this function, it will return a uniqueId from either interface: interface ReadOnlyInfo { item ...

Resolving parent routes in Angular 2

I am encountering an issue with my code. The 'new' route is a child route for the 'users' route. The 'users' route has a resolver, and everything works fine up to this point. However, after successfully creating a new user, ...

The requested resource on localhost does not have the 'Access-Control-Allow-Origin' header

I'm having trouble connecting to the Ebay API from my local server. Every time I try, I encounter this error message: The requested resource does not have the 'Access-Control-Allow-Origin' header. This means that the origin 'http://l ...

The type '{}' cannot be assigned to type 'IntrinsicAttributes & FieldsProp'. This error message is unclear and difficult to understand

"The error message "Type '{}' is not assignable to type 'IntrinsicAttributes & FieldsProp'.ts(2322)" is difficult to understand. When I encountered this typeerror" import { useState } from "react"; import { Card } fr ...

Struggling to Decode Octet-stream Data in Angular 6 HttpClient: Encountering Parsing Failure with Error Prompt: "Failed to parse HTTP response for..."

Is there a way to make a non-JSON request to the server using Angular 6 HttpClient (@angular/common/http) in order to receive an Octet-stream? Below is the code I have tried: getFile(file: any) { let headers = new HttpHeaders({ 'Content-T ...

The parameter type 'router' cannot be replaced with the type 'typeof ...'. The 'param' property is not included in the type 'typeof'

I'm currently working on a node application using TypeScript and have set up routing in a separate file named 'route.ts' import home = require('../controller/homeController'); import express = require('express'); let ro ...

Caught off guard by this promise: TypeError - Attempting to access a property that does not exist in my Ionic 2 application

I'm encountering an issue with native Facebook login that displays the following error message: Uncaught (in promise): TypeError: Cannot read property 'apply' of undefined I have shared my entire project code below. Although I am able to ...

Craft fresh items within HTTP request mapping

I am currently working on a function that subscribes to a search api. Within the map function, my goal is to transform items into objects. I haven't encountered any errors in my code, but the response always turns out empty. Here's the snippet o ...

The automatic filtering feature does not kick in when the sorting is changed

I've been working on an app that features a video database, allowing users to filter videos by category and sort them by rating. https://i.sstatic.net/cESZT.png Currently, the filtering system works fine once the options are changed. However, there ...

It is possible that the object may be null, as indicated by TS2531 error

I was interested in using QrReader to scan a file based on [https://github.com/Musawirkhann/react_qrcode_generation_scanner This code is written in react, but I wanted to use it with tsx. However, when attempting to implement it, I encountered an error: ...

What is the best way to retrieve the index of the chosen option from a select element in Angular when

My Angular application includes a simple <select> element using Material design: <mat-form-field> <mat-label>Type</mat-label> <mat-select placeholder="Type" formControlName="type" name="type" id="name"> <mat-option ...

Electron and React: Alert - Exceeded MaxListenersWarning: Potential memory leak detected in EventEmitter. [EventEmitter] has 21 updateDeviceList listeners added to it

I've been tirelessly searching to understand the root cause of this issue, and I believe I'm getting closer to unraveling the mystery. My method involves using USB detection to track the connection of USB devices: usbDetect.on('add', () ...

How to implement a Typescript interface without necessarily implementing the parent interfaces

Within my current project, I have defined the following interfaces: interface foo { fooProperty: number; fooFunction(): void; } interface bar extends foo { barProperty: string; barFunction(): void; } Now, I am interested in creating a class like ...

Tips on managing both the ionic 3 and ionic 4 versions cohesively on my device

Currently, I am utilizing multiple apps with ionic 3 version and everything is working smoothly. However, for my upcoming project, I am interested in using ionic 4 without uninstalling ionic 3. When attempting to install ionic 4 locally using the command b ...

Issue with the code: Only arrays and iterable objects are permitted in Angular 7

Trying to display some JSON data, but encountering the following error: Error Message: Error trying to diff 'Leanne Graham'. Only arrays and iterables are allowed Below is the code snippet: The Data {id: 1, name: "Leanne Graham"} app.compone ...

Assign a value to a FormControl in Angular 6

I have 60 properties linked to 60 controls through the mat-tab in a form. When it comes to editing mode, I need to assign values to all the controls. One approach is as follows: this.form.controls['dept'].setValue(selected.id); This involves l ...

Troubleshooting TestBed: Resolving the StatusBar Provider Error

After reading an informative article on testing Ionic2 projects with TestBed, I encountered difficulties when trying to replicate the example in my own environment. When attempting to initiate tests at Step 3, I encountered the error message stating "No pr ...

When attempting to parse a file name using a regular expression in TypeScript (or even plain Node.js), the unexpected outcome is a

Looking to extract language information from a filename? Check out this simple construct: The structure of my language.ts model is as follows: export interface Language { language?: string; region?: string; } The function designed for parsing the fi ...

What is the best way to link labels with input fields located separately in Angular?

Imagine a scenario where labels and form fields are being created in a *ngFor loop, as shown below: app.component.ts export class AppComponent { items = ['aaa', 'bbbbbb', 'ccccccccc'] } app.component.html <div class ...

What is the best way to update placeholders in Angular 8+?

I have a collection of items: a = ['apple', 'mango', 'grape', 'papaya', 'banana', 'cucumber']. An input element is present with a placeholder stating select from fruits (the array elements should ...