Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular error TS2564: Property 'users' has no initializer and is not definitely assigned in the constructor

I am using angular to built this app using this example from "https://coursetro.com/posts/code/171/Angular-7-Tutorial---Learn-Angular-7-by-Example".
Its an exact code but I am still getting an error for "user:Object"

How can I fix this error?

error TS2564: Property 'users' has no initializer and is not definitely assigned in the constructor.

12 users: Object; ~~~~~

Here is the exact code as per website:
import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
  //h1Style:boolean = false;

  users: Object;

  constructor(private data: DataService) { }

  ngOnInit(): void {
    this.data.getUsers().subscribe(data => {
        this.users = data
        console.log(this.users);
      }
    );
  }


}

My Angular based on ng version: Angular CLI: 11.1.2

Node: 14.15.4

OS: win32 x64

Angular: 11.1.1

... animations, common, compiler, compiler-cli, core, forms

... platform-browser, platform-browser-dynamic, router

Ivy Workspace: Yes

Package Version


@angular-devkit/architect 0.1101.2

@angular-devkit/build-angular 0.1101.2

@angular-devkit/core 11.1.2

@angular-devkit/schematics 11.1.2

@angular/cli 11.1.2

@schematics/angular 11.1.2

@schematics/update 0.1101.2

rxjs 6.6.3

typescript 4.1.3

like image 340
user244394 Avatar asked Feb 04 '21 18:02

user244394


People also ask

Has no initializer and is not definitely assigned in the constructor angular?

The error "Property has no initializer and is not definitely assigned in the constructor" occurs when we declare a class property without initializing it. To solve the error, provide an initial value for the class property, e.g. name: string = 'James'; or use a non-null assertion.


2 Answers

As @alcfeoh pointed out in the comments, you are getting this error because you are defining a variable but not declaring a value for it. The short answer is if you don't want to declare a value, then... just bang it:

users!: Object;

The reason why typescript throws this error is to prevent the following:

someNumber: number;

If there is no declaration included then the value of someNumber will be undefined even though we have explicitly not listed this type as someNumber: number | undefined;. But in many other languages, someNumber would receive a default value like 0. However that is not how Javascript works. If in this scenario you were to do someNumber + 1 the result would be null.

like image 96
Zze Avatar answered Oct 20 '22 15:10

Zze


u should add this code below tsconfig.json/"compilerOptions"

"strictPropertyInitialization": false,
like image 33
Berk Cinaz Avatar answered Oct 20 '22 15:10

Berk Cinaz