The variable 'user' is being accessed before being properly initialized - in Angular

I've been doing some research on Google and StackOverflow to try and troubleshoot this error, but I'm still having trouble getting it fixed. Can anyone provide assistance?

Below is the content of my auth-service.ts file:

import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { LoginService } from './login.service';
import { User } from '../interfaces/Ilogin';

@Injectable({
  providedIn: 'root'
})
export class AuthService implements  CanActivate {
  user: User;
  constructor(public loginService: LoginService, public router: Router) {}
  canActivate(): boolean {
    this.loginService.loggedIn.subscribe(next => {
      this.user = next;
    });
    if (this.user) {
      return true;
    }
   this.router.navigate(['home']);
   return false; 
  }
}

Next, let's take a look at my login.component.ts file:

import { Component, OnInit, Inject } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { LoginService } from '../services/login.service';
import { FormBuilder, FormGroup } from '@angular/forms';
import { Router } from '@angular/router';
import { User } from '../interfaces/Ilogin';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
  loginForm: FormGroup;
  user = {} as User;
  constructor(
    public dialogRef: MatDialogRef<LoginComponent>,
    @Inject(MAT_DIALOG_DATA) public data: any, 
    private loginService: LoginService, 
    private fb: FormBuilder,
    private router: Router) {}

    ngOnInit() {
      this.loginForm = this.fb.group({
        mobileNumber: [''],
        password: ['']
      })
    }
    login(){
      if (this.loginForm.valid){
        this.user.mobileNumber = this.loginForm.value.mobileNumber;
        this.loginService.loggedIn.next(this.user);
        this.onNoClick();
      }
    }

  
  onNoClick(): void {
    this.dialogRef.close();
  }
}

Moving on to my Ilogin.ts interface file:

 export interface User {
    mobileNumber: string;
  }

Lastly, here is my login.service.ts file:

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
import { User } from '../interfaces/Ilogin';

@Injectable({
providedIn: 'root'
})
export class LoginService {
 user: User;
 loggedIn = new BehaviorSubject(this.user);
 constructor() { }

isLoggedIn(): boolean {
 console.log(this.loggedIn);
 return true;
}
}

The specific error message you're receiving is:

src/app/services/login.service.ts:10:39 - error TS2729: Property 'user' is used before its initialization.

loggedIn = new BehaviorSubject(this.user); ~~~~

src/app/services/login.service.ts:9:3 user: User; ~~~~ 'user' is declared here.

Answer №1

In my opinion, the issue stems from the login.service class because you are assigning the variable loggedIn to a user object that has not been initialized.

To fix this, you can try initializing it like so:

loggedIn = new BehaviorSubject(null);
.

If you do not need to have your user object initialized at the start, consider using a Subject instead of a BehaviorSubject.

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

The specified control name formControlName in the Angular reactive form cannot be located

Having encountered this issue multiple times on Stack Overflow without any success, I am reaching out for help to identify what I might be doing wrong. In my component : ngOnInit() { this.companyCreatForm = this._formBuilder.group({ name: [null, ...

Having trouble importing the hash-set module in TypeScript/SystemJS?

In the midst of developing an Aurelia project with TypeScript to generate JavaScript, I decided to incorporate another custom library called 'hash-set' (installed using jspm install npm:hash-set --save). However, I encountered difficulties in act ...

Issue with Angular2: Child components are not sending events to parent components

There are two components, one nested within the other. A click function in the child component triggers an event emitter that emits a string. In the parent template, the event emitter is used to call a function in the parent component that logs a simple me ...

Strange Appearance of Angular Material Slider

I am experiencing some issues with my slider and I'm not exactly sure what's causing them. [] .big-container { display: block; padding-left: 10px; padding-right: 10px; padding-top: 10px; margin-bottom: 10px; } .question { display ...

The KeyConditionExpression is invalid due to the use of multiple attribute names within a single condition

I am trying to query a DynamoDB table using GraphQL TableName: "JobInfo", IndexName: "tableauGSI", KeyConditionExpression: "tableauGSI_Tableau = tableau AND #D BETWEEN :startDate AND :endDate", ExpressionAttributeNames: { "#D": "date" }, ...

Leveraging Angular 2 to retrieve information from mongoDB

I recently finished setting up my nodejs project which includes a database and some data. The database was created using the following URL: mongodb://localhost:27017/ Check out the code snippet below: var MongoClient = require('mongodb').MongoC ...

Tips for displaying backend error messages on the frontend

I am facing an issue with returning error messages from the backend to the frontend in my Angular project. The specific requirement is to display an error message when the value of msisdn is not eligible for renewal. Currently, the hardcoded error message ...

Acquire the URL using Angular within a local environment

I am currently working on a basic Angular project where I have a JSON file containing some data. [{ "name": "Little Collins", "area": "Bronx", "city": "New York", "coverImage": "https://images.unsplash.com/photo-1576808597967-93bd9aaa6bae?ixlib=rb-1.2.1&a ...

Implementing endless scrolling in Angular 5 using data fetched from a httpClient call

Looking to incorporate infinite scroll using a large JSON dataset in Angular 5. The goal is to display the first 5 entries initially, and as the user scrolls, load the next 5. I came across this library: https://github.com/orizens/ngx-infinite-scroll, but ...

Error message "Could not locate module while constructing image in Docker."

I've encountered an issue while working on my nodeJS Typescript project. After successfully compiling the project locally, I attempted to create a docker image using commands like docker build or docker-compose up, but it failed with a 'Cannot fi ...

How can I define the type of a constructor that requires a parameter in TypeScript?

Having identified the issue, let's focus on a minimal example: // interfaces: interface ClassParameter{ x:number } interface ClassParameterNeeder{ y:number } type ClassParameterConstructor = new () => Cla ...

Guide on Integrating RDLC Reports with Angular 7

I currently have a window application that contains multiple RDLC reports. As I am transitioning this window application to Angular 7, I am wondering if there is a way to utilize my existing RDLS reports in Angular 7? While I have come across suggestion ...

Tips on integrating ActiveX controls in Angular

I built my project using Angular 6 and TypeScript in Visual Studio Code. The browser being used is IE11. Unfortunately, when I try to run the code written in app.component.html, it doesn't work as expected. The HTML code causing the issue is: <d ...

JavaScript: Navigating function passing between multiple React components

I'm currently working on a React Native application utilizing TypeScript. In my project, there is a component named EmotionsRater that can accept two types: either Emotion or Need. It should also be able to receive a function of type rateNeed or rate ...

Ways to create a scrolling effect for a datalist dropdown menu

My HTML datalist shows various career paths, but the number of options is too long. I want to add a scrolling effect to it. I have looked for ways to do this, but I read that CSS cannot be applied to datalists. Is it possible to apply styles using jQuery i ...

A guide to implementing asynchronous validation with reactive/model-driven forms in Angular 2

I'm working on implementing an email input validator that will check if the entered email already exists in the database by using an API. Here's what I have: Validator Directive import { Directive, forwardRef } from '@angular/core'; ...

Error encountered: UI-Router state's 'includes' property is not recognized as a valid property in the StateDeclaration type

Prior to initiating the state transition, it is necessary to validate whether the target state falls under a parent state. The MatchCriteria is as follows: this.transition.onStart({ to: function(state) { return state.includes.parentstate; } },() = ...

Compiler error occurs when trying to pass props through a higher-order component via injection

Recently, I have been experimenting with injecting props into a component using a higher order component (HOC). While following this insightful article, I came up with the following HOC: // WithWindowSize.tsx import React, {useEffect, useMemo, useState} fr ...

What are the best strategies for combining multiple TypeScript class decorators?

I have a set of unique class decorators that I apply to multiple classes. It looks something like this: @awesome @cool @amazing export class MySpecialClass { /* ..... */ } However, since I use these three decorators across many classes, I want to condens ...

Is it possible to manipulate an Object within Object typescript?

My recent project involved working with React and Typescript to fetch data from an API. Once the data is fetched, it is saved as an object called coin. However, I encountered a situation where the data may not be fully loaded, resulting in coin being null. ...