TS2531:在 Angular 12 的 html 中注入数据时,对象可能为"空"



此代码从Github api获取Github存储库,但当我将代码中的[repoUrl]更改为[repoUrl]时,我收到了一个错误,该错误表明对象可能为null!然后它成功地编译了,但在我运行搜索时没有列出存储库,你知道哪里可能出了问题吗?

回购组件html:

<div *ngFor="let repo of repos" class="list-group">
<a
[href]="repo.html_url"
target="_blank"
class="list-group-item list-group-item-action"
>
{{ repo.name }}
</a>
</div> 

homecomponent html:

<div class="col col-md-8">
<app-repos *ngIf="user" [repoUrl]="user.repos_url"></app-repos>
</div>

回购组件ts文件:

export class ReposComponent implements OnInit, OnChanges {
@Input() repoUrl!: string;
repos:any = [];
constructor(
private githubService: GithubService,
private ref: ChangeDetectorRef
) {}
ngOnInit(): void {}
ngOnChanges(): void {
if (this.repoUrl) {
this.githubService.getRepos(this.repoUrl).subscribe(
(repos:any= []) => {
this.repos = repos;
this.ref.detectChanges();
},
(err) => {
console.log(err);
}
);
}

Angular默认启用严格的类型检查,其中包括strictNullChecks,这意味着您必须显式检查变量是否为空,或者通过添加!非空断言告诉typescript变量不会为空

您可以在tsconfig中全局禁用此功能。

{
...
"strictNullChecks": false,
}

或添加非空断言

user!: User;

或添加默认值

user: User = {} //empty object;

在模板中添加ngIf?(elvis运算符(不起作用,请使用$any来消除错误

<app-repos *ngIf="user" [repoUrl]="$any(user).repos_url"></app-repos>

$any-是一个角度模板功能,它可以简单地告诉typescript将类型视为any,并在编译时忽略错误。

阅读严格的零位检查,也阅读角度中的严格类型检查

这一定是Ivy AoT造成的。

选项1:<ng-container>

尝试将*ngIf封装在<ng-container>中。

<div class="col col-md-8">
<ng-container *ngIf="!!user">
<app-repos [repoUrl]="user.repos_url"></app-repos>
</ng-container>
</div>

选项2:安全导航操作员

访问属性时,请尝试使用安全导航运算符?.

<div class="col col-md-8">
<app-repos *ngIf="user" [repoUrl]="user?.repos_url"></app-repos>
</div>

我还没有对此进行测试,它可能无法解决问题。

问题是分配给ts文件中repoUrl的类型I

我把它改成了";任何";从";字符串";它起到了的作用

export class ReposComponent implements OnInit, OnChanges {
@Input() repoUrl!: any;
repos:any = [];
constructor(
private githubService: GithubService,
private ref: ChangeDetectorRef
) {}
ngOnInit(): void {}
ngOnChanges(): void {
if (this.repoUrl) {
this.githubService.getRepos(this.repoUrl).subscribe(
(repos:any= []) => {
this.repos = repos;
this.ref.detectChanges();
},
(err) => {
console.log(err);
}
);
}
}

最新更新