Angular strictPropertyInitialization - best practices for initializing class members?

When initializing a component, I need to retrieve user information. However, with the Angular strict mode in place, I'm uncertain about where to fetch this data.

I have considered 3 options. But which one is the most appropriate? Is there another alternative?

#1 This option involves calling the service method directly on initialization of the userInfo.

export class NavComponent implements OnInit {
  public userInfo$: Observable<LoggedInUser> = this.sessionService.getUserInformation();

  constructor(private sessionService: SessionService) {}

  ngOnInit(): void {}
}

#2 I believe it would be more beneficial to initialize this in the constructor:

export class NavComponent implements OnInit {
  public isMobileMenuCollapsed = true;
  public userInfo$: Observable<LoggedInUser>;

  constructor(private sessionService: SessionService) {
    this.userInfo$ = this.sessionService.getUserInformation();
  }

  ngOnInit(): void {}
}

#3 In the ngOnInit method rather than the constructor. However, for this solution, I also require the Definite Assignment Assertion:

export class NavComponent implements OnInit {
  public isMobileMenuCollapsed = true;
  public userInfo$!: Observable<LoggedInUser>;

  constructor(private sessionService: SessionService) {
  }

ngOnInit(): void {
  this.userInfo$ = this.sessionService.getUserInformation();
}

}

Which of these options should I implement in my code?

Answer №1

In short, go with option #1.

Which option is the right one?

If you're exclusively using userInfo$ in your HTML template, then theoretically all three options should work.

Why is that?

Since template code runs after ngOnInit, by then userInfo$ should have already been initialized in all three scenarios.

So, which option is superior?

Both #1 and #2 are essentially the same as they both initialize userInfo$ in the constructor. I find #1 preferable as it eliminates redundancy in the code.

#3 differs slightly as the initialization doesn't occur in the constructor. This could potentially lead to subtle bugs if you end up utilizing userInfo$ within the component (like in ngOnChanges which is invoked before ngOnInit).

Answer №2

Are you facing a real problem? Could it be related to a type mismatch in your template when using the async pipe?

Remember, the async pipe might return null, indicating that the issue lies not with your observable but with the result of the pipe.

How can you resolve this issue?

To address this, consider adding a *ngIf directive on the element or a parent element and utilize the output. By using *ngIf, you ensure that the data type does not contain null anymore.

<ng-container *ngIf="data$ | async as data">

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

Express server experiencing issues with generating Swagger documentation

I've been working on an Express API and decided to implement documentation using Swagger and JSDoc. However, the documentation is not working as expected. Here's how I've set it up: docs.ts: import swaggerJSDoc, { Options } from "swagg ...

The interfaces being used in the Redux store reducers are not properly implemented

My Redux store has been set up with 2 distinct "Slice" components. The first one is the appSlice: appSlice.ts import { createSlice, PayloadAction } from "@reduxjs/toolkit"; import type { RootState } from "./store"; export interface CounterState { value ...

What are the benefits of initializing my Angular2 reactive form in the constructor instead of ngOnInit?

According to several responses, it is recommended to initiate the initial functions of an Angular2 application within the ngOnInit() method, reserving the constructor specifically for dependency injection tasks. However, the Reactive Forms tutorial I am c ...

The TypeScript error reads: "An element is implicitly assigned the 'any' type because an expression of type 'any' cannot be used to index a specific type."

[Hey there!][1] Encountering this TypeScript error message: { "Element implicitly has an 'any' type because expression of type 'any' can't be used to index type '{ 0: { image: string; title: string; text: string; }; 1: { ...

Handling errors within classes in JavaScript/TypeScript

Imagine having an interface structured as follows: class Something { constructor(things) { if (things) { doSomething(); } else return { errorCode: 1 } } } Does this code appear to be correct? When using TypeScript, I en ...

Next.js API routes encountering 404 error

I am encountering an issue with calling my route API (404) in my new nextjs project. The route API can be found at src/app/api/speed.js Within my page src/app/page.tsx, I have the following code snippet: fetch("api/speed").then(res=>res.json ...

Looking for a solution to the error message: "X is not able to be assigned to the type 'IntrinsicAttributes & Props'"

Greetings everyone! I need some assistance in setting up single sign-on authentication using React, Azure AD, and TypeScript. I'm encountering a type error in my render file and I'm unsure of how to resolve it. Below is the specific error message ...

Issue with Switch Map in Angular 2 and RxJS

I'm currently implementing an infinite scrolling feature in my application using a specific component for managing scroll events. When the scroll reaches the bottom of the div, I trigger a function to fetch more data. Everything seems to be working fi ...

Error: Unable to retrieve options using this.getOptions function. This issue is unrelated to Vue, it is occurring within

Required Modules "dependencies": { "express": "^4.17.1", "express-static-gzip": "^2.1.1", "react": "^17.0.2", "react-dom": "^17.0.2", "reac ...

What are the best ways to maximize a web worker's ability to handle multiple tasks at once

I'm currently working on implementing a Web-Worker to handle its state while also managing multiple asynchronous requests. worker.ts file let a =0; //state of the worker let worker=self as unknown as Worker; worker.onmessage =(e)=>{ console ...

Encountering Kubernetes Ingress Error: 502 Bad Gateway - Connection Refused

I am facing an issue while trying to access my Angular front-end deployed on an AKS cluster at Path / with the service named lawyerlyui-service. The cluster is using nginx deployed via HELM with the official chart () I have other backend .net core services ...

Solutions for Utilizing Generic Mixins in Typescript

As a newcomer to Typescript, I have encountered an issue with mixins and generics. The problem became apparent when working on the following example: (Edit: I have incorporated Titian's answer into approach 2 and included setValue() to better showcas ...

When you initiate an Angular 8 project on a Windows 10 system, it generates extra files

Just a few days ago, I made the decision to transition from using an Ubuntu virtual machine for my Angular and development projects to working on Windows. The reason behind this shift was that I already had Node installed along with Git and other necessary ...

Prisma - Modify a single resource with additional criteria

Is it feasible to update a resource under multiple conditions? Consider the tables below: +----------+----------+ | Table1 | Table2 | +----------+----------+ | id | id | | param1T1 | param1T2 | | param2T1 | param2T2 | | idTable2 | ...

Beginning external plugin in Angular 4 application

Is it possible to incorporate an external plugin into an Angular 4 application? I am looking to utilize the niceScroll plugin for a scrollable div, which is defined within a component. <div class="d-flex" id="scrollable"> <app-threads-list> ...

NGRX reducer avoids generating errors due to incorrect assignments

My experience with ngrx is relatively new. In my typical TypeScript work, I usually encounter an incorrect assignment error like the one below due to a missing property in the interface declaration: interface IExample { count: number; } let initialState ...

When sending data from Angular to the server, the request body appears to be blank

To transfer data from the client side (using Angular) to a Node.js server, I have set up a service in Angular. export class AddTaskService { constructor(private http: HttpClient) { } url = 'http://localhost:3000/tasks'; posttasks(task) { ...

Changing return values with Jest mocks in TypeScript

Here I am again with a very straightforward example. In summary, I require a different response from the mocked class. Below is my basic class that returns an object: class Producer { hello() { return { ...

Having trouble deploying my MEAN stack application on Heroku due to a MongoNetworkError: unable to establish a connection to the

Encountering difficulty connecting to MongoDB for application deployment, receiving error message "MongoNetworkError: failed to connect to server [localhost:27017] on first connect [Error: connect ECONNREFUSED 127.0.0.1:27017". What are potential issues ca ...

Is it necessary to enable validation for an Angular reactive form toggle?

Can you help with this issue I'm having? I have a radio button that asks the user if they have a massage certificate. If they answer yes, a file input should be displayed. By default, the file input should not be required, but if the user selects yes, ...