我有一个父组件 (app.component) 发出 http 请求,将结果分配为 this.stats,然后将其作为 prop 传递给子组件 (progression.component)。我的问题似乎是我的孩子在从父母那里获取任何数据之前正在渲染,导致孩子抛出错误并中断。
即当我在子组件中记录 prop 时,我得到 -> {} [[Prototype]]: Object
我只是缺乏经验,但由于我的所有组件都使用 ngOnInit() 并订阅了可观察量,我认为孩子应该等待父母完成?我不确定如何修复这样的问题,因为它存在于各个组件中,并且不是我可以合并我认为的可观察量的情况......任何见解都会很棒:)谢谢!
父组件
export class AppComponent {
title = 'pctothemoon';
stats: any
constructor(private specsService: SpecsService) {}
ngOnInit(): void {
this.specsService.getStats().subscribe((res)=>{this.stats=res})
}
}
Run Code Online (Sandbox Code Playgroud)
子组件
export class ProgressionComponent {
@Input() stats: any;
oldStats: any;
constructor(private specsService: SpecsService) { }
ngOnInit(): void {
this.specsService.getProgress().subscribe((res)=>{console.log(res)})
}
AfterViewInit(){
this.specsService.postUpdates(this.stats).subscribe((res)=>{console.log("updated stats", res)})
}
}
Run Code Online (Sandbox Code Playgroud)
作为参考,我还将包含我的 service.ts 以在后台显示我的 http 请求
export class SpecsService {
private apiUrl = 'http://localhost:3000'
constructor(private http:HttpClient) {}
getStats():Observable<any>{
return this.http.get(`http://localhost:8888/fetchStats`)
}
postUpdates(stats):Observable<Object>{
//send stats to json server store
const url = `${this.apiUrl}/progressionData`; //json server collection location
return this.http.post(url,stats,httpOptions) + stats
}
getProgress(){
return this.http.get(`${this.apiUrl}/progressionData`)
}
}
Run Code Online (Sandbox Code Playgroud)
dan*_*y74 13
答案很简单。只需将子组件包装在 HTML 中的 *ngIf 内即可:
<ng-container *ngIf="!!stats">
<app-child-component [stats]="stats"></app-child-component>
</ng-container>
Run Code Online (Sandbox Code Playgroud)
条件是孩子需要的数据可用。这里,在数据可用之前不会创建子组件。
注意:在较新版本的 Angular 中,if 语句有新的语法,尽管旧*ngIf语法也可以使用