我使用angular来构建这个应用程序使用这个例子从"https://coursetro.com/posts/code/171/Angular-7-Tutorial---Learn-Angular-7-by-Example".
这是一个确切的代码,但我仍然得到一个错误"user:Object">
如何修复此错误?
错误TS2564:属性'users'没有初始化式,并且不是在构造函数中明确赋值。
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);
}
);
}
}
我的Angular基于ng版本:Angular CLI: 11.1.2
节点:14.15.4
操作系统:win32 x64
角:11.1.1
…动画、common、compiler、compiler-cli、core、forms
…平台浏览器,平台浏览器动态,路由器
Ivy Workspace: Yes
包 版本
@angular-devkit/建筑师0.1101.2
@angular-devkit/build-angular 0.1101.2
@angular-devkit/核心 11.1.2
@angular-devkit/图表11.1.2
@angular/cli 11.1.2
@schematics/角 11.1.2
@schematics/更新 0.1101.2
rxjs 6.6.3
打印稿 4.1.3
正如@alcfeoh
在评论中指出的那样,您正在获得此错误,因为您正在定义变量但未为其声明值。简短的回答是,如果你不想声明一个值,那么…按一下:
users!: Object;
typescript抛出这个错误的原因是为了防止以下情况:
someNumber: number;
如果没有包含声明,则someNumber
的值将是未定义的,即使我们没有显式地将该类型列为someNumber: number | undefined;
。但是在许多其他语言中,someNumber将接收一个默认值,如0
。然而,这不是Javascript的工作方式。如果在这种情况下,您要执行someNumber + 1
,结果将是null
。
你应该在tsconfig.json/"compilerOptions"下面添加这段代码
"strictPropertyInitialization": false,