Utilize TypeScript to generate an array from an Enum and subsequently employ it as a parameter in a service invocation

I am working on an Angular component that utilizes a simple service to retrieve data based on an Enum parameter.

export enum AgeEnum {
    UNDER_18 = 'UNDER_18',
    ABOVE_18 = 'ABOVE_18'
}

Within my component, I have the following setup:

private ageArray = Object.keys(AgeEnum);

private restrictionsWrapper: RestrictionsWrapper;

constructor(private restrictionsService: RestrictionsService) {
}

ngOnInit(): void {
    this.getRestrictionsForAge(this.ageArray);
}

private getRestrictionsForAge(ages: string[]) {
    for (const age of ages) {
        this.restrictionsService.getRestrictions(age as AgeEnum)
            .subscribe((options) => {
                    this.restrictionsWrapper.restrictions = options.restrictions;
                }, () => {
                    this.restrictionsWrapper.restrictions = null;
                }
            );
    }
}

The UI Service method is defined as follows:

getRestrictions(age: AgeEnum): Observable<RestrictionsWrapper> {
    const params = new HttpParams().set('age', age);
    return this.http.get<RestrictionsWrapper>(BackendRoute.RESTRICTIONS, {params: params});
}

This is the model for RestrictionsWrapper:

export interface RestrictionsWrapper {
    restrictionDocuments: string[];
    blocked: boolean;
}

The goal is to load different sets of restrictions based on the age, without duplicating methods. However, there seems to be an error:

Unhandled error occured. TypeError: Cannot set property 'restrictions' of undefined

Any suggestions on what might be incorrect or if using

this.restrictionsService.getRestrictions(age as AgeEnum)
is the best approach?

Answer №1

It seems like the issue lies in your RestrictionsWrapper being an interface. An interface is meant to describe values and functions that classes must implement, but it is not an object itself.

The error message

TypeError: Cannot set property 'restrictions' of undefined
indicates that you are trying to assign a value to a property of an undefined variable, like this: undefined.restrictions = VALUE.

To resolve this problem, you have two options:

First:

// Initialize your variable with an empty object
private restrictionsWrapper: RestrictionsWrapper = {};

Second:

In your component:

private restrictionsWrapper: RestrictionsWrapperClass;

constructor(private restrictionsService: RestrictionsService) {
    this.restrictionsWrapper = new RestrictionsWrapperClass();
}

In your restriction.api.ts:

export class RestrictionsWrapperClass implements RestrictionsWrapper {

    restrictionDocuments: string[];
    blocked: boolean;

    constructor() {
        // Set default values if needed
        this.restrictionDocuments = [];
        this.blocked = false;
    }

}

Answer №2

insert

Create a new instance of RestrictionsWrapper inside the constructor or ngOnInit() of the controller, or within the getRestrictionsForAge() method.

The issue arises from attempting to set properties of restrictionsWrapper before it has been instantiated.

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

strategies for sharing data in Angular 2

Seeking advice on data sharing within various components of an Angular 2 application. At the moment, my app structure is similar to that shown in this tutorial, where the AppComponent is bootstrapped by Angular and multiple components are routed from there ...

Ensure that enums in Typescript are initialized explicitly

Is there a way to explicitly initialize the following enum in typescript? enum BloodGroup { OPositive = "O +ve", ONegative = "O -ve", APositive = "A +ve", ANegative = "A -ve", } I attempted something like this (I know it won't wo ...

Why am I restricted to adjusting mat-elevation settings within the component's CSS exclusively?

In my Angular 8 project, I am utilizing Angular material to enhance the design of my material cards. To set up the shadow effect on these cards, I am using the elevation helper mixins provided in the documentation: https://material.angular.io/guide/elevati ...

The absence of the google-services.json file has rendered the Google Services Plugin inoperable. Attempted search location:

Having an issue while trying to integrate my app with Firebase. The error message keeps indicating: > File google-services.json is missing. For a more detailed view of the error, please refer to the image below: https://i.stack.imgur.com/sgNYu.jpg D ...

Using a for-loop in Typescript to iterate over objects in an array

Consider an Array structured as follows: let bodyDataAnswer = { 'answers':[{ 'question_id':this.verifyCustomer.questions[0].id, 'int_result':this.verifyCustomer.questions[0].answer_template.answers["0"].int_result, ...

Received an error while using Mongoose 6 $group with Typescript stating that the property '_id' is not compatible with the index signature

Recently, I've been transitioning from JavaScript to TypeScript and also upgrading from mongoose 5.8 to version 6.1. The code snippet below used to work perfectly before: let getActionsTakenByApp = (store_url: string) => { return AppAction.aggr ...

A guide to implementing Typescript Generics in modifier functions

I am searching for a solution to properly enforce strong typing in the following scenario. I believe Typescript Generics might be the way to go here. interface Person { name: string; age: number; } const person: Person = { name: "John", ...

What are the drawbacks of starting with Angular CLI?

Contemplating whether to incorporate Angular CLI into my upcoming project has been on my mind. My main motivation for considering it is to bypass the complexities of setting up a new project and instead focus on mastering the new version of Angular while c ...

Tips for associating an identifier with a preexisting symbol in a TypeScript compiler transformer

Trying to implement a typescript compiler transform with the typescript compiler API has been challenging. Despite emitting new Identifier nodes to the final .js file, they appear to lack symbol binding information, resulting in incorrect output. For inst ...

Errors detected while attempting to install dependencies using pnpm: modules unspecified

I recently decided to experiment with using pnpm instead of npm for my new projects, but I've encountered an issue. Let's take my nuxt project as an example. First, I set up my project using the command: pnpx nuxi init my-project Then, I insta ...

Creating a standard arrow function in React using TypeScript: A Step-by-Step Guide

I am currently working on developing a versatile wrapper component for Apollo GraphQL results. The main objective of this wrapper is to wait for the successful completion of the query and then render a component that has been passed as a prop. The componen ...

Developing an Angular directive that accepts a function parameter using TypeScript

I've been attempting to integrate an Angular function parameter into a TypeScript directive, but it seems like my syntax is off. Here's an example of the directive code I'm working with: export class CustomDirective implements ng.IDirective ...

The functionality of GetStaticProps with Typescript is only operational when defined as an arrow function, rather than a function

The documentation for GetStaticProps in NextJs explains it as a function declaration. When trying to add types to it, the following code snippet results: export async function getStaticProps(): GetStaticProps { const db = await openDB(); const fa ...

Tips for changing a created Word file with Docxtemplater into a PDF format

Hey there! I am currently in the process of building a website with Angular.js and have successfully managed to generate a word document from user input. Everything was working fine until I encountered an issue. I now need to provide a way for users to pr ...

Utilizing Class Validator in NestJS: A Guide to Injecting Services into Validator Constraint Interfaces

I have been attempting to inject my users service into my validator constraint interface, but I am encountering issues with getting it to work: import { ValidatorConstraintInterface, ValidatorConstraint, ValidationArguments, registerDecorator, ValidationO ...

What could be causing the Angular error related to this HttpHeader?

Is there anyone who can assist me with why I am encountering an error in my Angular code while trying to use HttpHeaders to read the response status from the backend? Here is the specific error message: https://i.sstatic.net/tQu5t.jpg import { Injectable ...

Prevent a TypeScript generic object from containing a specific property

I've encountered a situation where I need to create a generic function that accepts an object as a parameter, but with the condition that the object cannot have properties in the format __property__. Currently, my approach is: type RemoveProps = { ...

Is there a way to incorporate npm install --force into the process when running ionic build android?

When I ran the following command: ionic capacitor sync android I encountered conflicts with certain modules: C:\Users\DELL\Documents\inspecciones\inpecciones-app>ionic capacitor sync android > npm.cmd i -E @capacitor/<a h ...

"Discovering the secrets of incorporating a spinner into Angular2 and mastering the art of concealing spinners in Angular

When experiencing delay in image loading time, I need to display a spinner until the image loads completely. What is the best way to achieve this on the Angular 2 platform? <div id='panId' class="container-fluid" > This section ...

Angular: Updating image tag to display asynchronous data

Utilizing Angular to retrieve user profile pictures from the backend, specifically Node.js/Express, has been mostly successful. However, there is one issue that I have encountered. The HTML displaying the profile picture does not re-render when the user up ...