Angular 9 ensures that the component template is validated and loaded before the constructor logic is executed

Recently switched from Angular 8 to Angular 9 (without IVY) and encountered some unusual errors indicating that services injected in components are undefined in getters. Upon investigation, I discovered that the getter is being called before the constructor.

I'm intrigued as to how this could happen.

@Component({
    selector: 'some-component',
    templateUrl: './some-component.pug'
})
export class SomeComponent {
    get someProp () {
        console.log('Getter called', { ...this.someService }); // 'Getter called' {}
        return this.someService.some;
    }

    constructor (private someService: SomeService) { console.log('Constructor called') }

}

// some-component.pug
{{ someProp }}

This will result in an error

TypeError: Cannot read property 'some' of undefined

UPDATE Upon further examination, it was discovered that this issue only occurs when using version 9 of ngrx:

"@ngrx/effects": "^9.2.0",
"@ngrx/store": "^9.2.0",
"@ngrx/store-devtools": "^9.2.0"

Answer №1

In my opinion, utilizing a question mark may be the key to resolving the error:

return this.someService?.some;

Alternatively, consider implementing lifecycle hooks like ngOnInit as they are triggered after the constructor.

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

Updating the value of a form control in Angular2

I am facing an issue when trying to create dynamic Angular 2 forms with controls and select boxes, like in this example on Plunker: <select class="form-control" ngControl="power"> <option *ngFor="#p of powers" [value]="p">{{p}}</o ...

Is there a way to access the badge hidden behind the collapsible menu in bootstrap 4?

After moving from bootstrap 3 to bootstrap 4, my items no longer align properly. I've scoured the entire Internet for a solution, but I've run out of options (and patience.. haha) This is how it currently looks: I want the badge to be positione ...

Tips for assigning a value to a Reactive Form control within Angular 6

I am looking to dynamically set the value of a text box when clicking on a button that is located outside of the form. How can I achieve this? <form [formGroup]='student' (ngSubmit)='click()'> <input type='text' form ...

What is the correct way to set the default function parameter as `v => v` in JavaScript?

function customFunction<T, NT extends Record<string, string | number | boolean>>( data: T, normalize?: (data: T) => NT, ) { const normalizedData = normalize ? normalize(data) : {}; return Object.keys(normalizedData); } customFuncti ...

Having difficulty using the Angular 6 "generic type elementref requires 2 type arguments" error message in my code

When attempting to use ElementRef, I included the following import statement: import { Component, OnInit, ElementRef, ViewChild } from '@angular/core'; I followed the examples and injected it into the constructor as shown: constructor(private ...

What is the best way to determine if the current page in Ionic 2 is being loaded from the sidemenu?

In my Ionic 2 application, there is a page that can be accessed either by clicking on a link in the sidenav or being active by default when the app is loaded. However, I want to implement an additional feature only when the page is accessed through the sid ...

Creating an image using the @aws-sdk/client-bedrock-runtime package is a simple process

Having crafted a BedrockRuntimeClient using typescript, I'm stumped on how to call upon the model and execute the command. const client = new BedrockRuntimeClient({ region: "us-east-1", apiVersion: '2023-09-30', ...

Insert a new item into the array located within an Observable entity

In my angular application, I have a page where I am showcasing an object that contains an array of comments within it. This object is loaded into my class as an Observable and then displayed in the HTML using: <div class="container-fluid mt--7" ...

Choose the ngModel option from the dropdown menu

I have a project where I need the first question from a list to be displayed automatically. I found an example of how to do this using the index, like so: <select> <option *ngFor="let answer of answers; let i = index" [value]="answer.id" [selec ...

An issue occurred while attempting to differentiate the '[object Object]'. Angular-11 Application only accepts arrays and iterables for this operation

When using *ngFor, I am facing an issue with fetching data from my component.ts to my component.html Interestingly, the same method works for one class but not for another. Let's take a look at my service class: export class FoodListService { priv ...

The issue of NestJS dependency injection not working within the MongooseModule.forFeatureAsync function call has been encountered

I'm having an issue setting up a pre-save hook on my User model. Here's the code snippet from my users.module.ts: @Module({ controllers: [ UsersController, ], exports: [ UsersService, ], providers: [ UsersService, ], imp ...

Testing the functionality of functions through unit testing with method decorators using mocha and sinon

I have a class method that looks like this: export class MyClass { @myDecorator() public async createItem(itemId: string, itemOptions: ItemOption[]): Promise<boolean> { // ... // return await create I ...

RxJS emits an array of strings with a one second interval between each emission

Currently, my code is set up to transform an Observable<string[]> into an Observable<string>, emitting the values one second apart from each other. It's like a message ticker on a website. Here's how it works at the moment: const ...

Encountered an issue while using OpenAPI 3.1 with openapi-generator-cli typescript-fetch. Error: JsonParseException - The token 'openapi' was not recognized, expected JSON String

I am interested in creating a TypeScript-fetch client using openapi-generator-cli. The specifications were produced by Stoplight following the OpenAPI 3.1 format. However, when I execute the command openapi-generator-cli generate -i resources/openapi/Attri ...

Necessary Typescript class property when executing code

Is there a way to determine if a class property is required in Typescript at runtime? export class A { public readonly ab?: number; public readonly ac?: number; public readonly ad: number; public readonly ae: number; } Can emitDecoratorMetadata o ...

Tips for inserting a property into an array of objects when it matches the specified ID

As someone new to Angular, I am encountering an issue and would appreciate some help. Here is an array of objects I am working with: signals = [{ 'signalID': '123' },{ 'signalID': '233' },{ 'signalID': &apo ...

Struggling with module dependencies in Nest.js

I have been diving into the documentation provided on the NestJs website, but I've noticed that it can be a bit scattered. My goal is to retrieve an RPG Character from a Mongo database using TypeORM. Unfortunately, I seem to be running into dependency ...

Sending boolean values from parent components to child components in Angular 2

Is there a way to pass boolean values from a parent to child component without involving the template file? I am familiar with the normal method of communication between parent and child components using the template file, but I am not sure how to achieve ...

What scenarios call for utilizing "dangerouslySetInnerHTML" in my React code?

I am struggling to grasp the concept of when and why to use the term "dangerous," especially since many programmers incorporate it into their codes. I require clarification on the appropriate usage and still have difficulty understanding, as my exposure ha ...

Invoke a custom AWS CodeBuild project in CodePipeline using a variety of parameters

Imagine having a CodePipeline with 2 stages structured like this: new codepipeline.Pipeline(this, name + "Pipeline", { pipelineName: this.projectName + "-" + name, crossAccountKeys: false, stages: [{ stageName: &apos ...