【发布时间】:2021-02-22 13:22:24
【问题描述】:
你对下面这个奇怪的问题有什么想法吗?
我正在将数据从父组件传递到子组件,该子组件从服务方法返回,将数据返回为Observable<DemoModel>。但是,在加载子组件时,数据未定义,仅在ngAfterViewInit 之后填充(我也尝试过通过此方法获取数据,但数据仍然未定义)。所以,我也尝试应用一些ngOnchanges 方法,但问题更多与从父组件检索到的数据在子组件加载时尚未准备好(我也尝试使用异步等而不是订阅。在加载子组件时我应该如何获取数据以使其准备就绪?
父子组件如下图:
家长比较
<child-component
[courses]="courses|async"
>
</child-component>
courses: any;
this.service.listCourses().subscribe((course: Course) => {
this.courses = course;
});
儿童补偿
private courses: any;
@Input()
set data(data: any) {
this.courses.next(data);
}
myControl = new FormControl('');
ngAfterViewInit() {
// >>> THIS THROWS ERROR AS this.courses is undefined
this.myControl.setValidators([
Validators.required,
forbiddenNamesValidator(this.courses)
]);
}
我也尝试在html中使用一些*ngIf,但是由于方法中使用了this.courses参数,因此检查html中的数据没有任何意义。
这个问题可能是subscribe方法引起的,不过我也试过用promise(不知道是不是用对了)。
【问题讨论】:
标签: javascript angular typescript