我试图根据将通过HTTP get调用检索的数据加载子组件。我正在使用服务进行HTTP调用并订阅组件的构造函数。但是ngif是在数据检索之前调用的。
所以我在ngif中应用了异步管道,但它触发了另一个错误。
服务代码:
GetContest(id){
return this.http.get(this.baseurl+id);
}
组件的构造函数:
this.service.GetContest(this.route.snapshot.paramMap.get('id')).
subscribe( (res)=> {
this.contest = res;
console.log(this.contest);
});
template ngif:
<app-beforecontest *ngIf="contest.startTime<date "></app-
beforecontest>
以上代码会产生错误:
TypeError: Cannot read property 'startTime' of null
此后,我像这样加入了异步管道:
<app-beforecontest *ngIf="(contest|async).startTime<date "></app-
beforecontest>
它正在生成错误:
ContestComponent.html:1 ERROR Error: InvalidPipeArgument: '[object
Object]' for pipe 'AsyncPipe'
at invalidPipeArgumentError
在处理异步响应并绑定模板的情况下,您也可以像这样使用安全的导航操作符-
<app-beforecontest *ngIf="contest?.startTime<date "></app-
beforecontest>