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
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.
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
.
u should add this code below tsconfig.json/"compilerOptions"
"strictPropertyInitialization": false,
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With