我试图使用app.component.ts中的视图子项将模块的组件中存在的属性(bookmarkedCount)值提供给app组件。但是我在读取app组件中的属性值时出错是未定义的。为什么会这样?
错误TypeError:无法在AppComponent.push读取属性'bookmarkedCount'。/ src / app / app.component.ts.AppComponent.ngAfterViewInit(app.component.ts:36)
app.component.ts
@ViewChild(ContainerComponent) private containerComponent:ContainerComponent;
ngAfterViewInit(): void {
this.count = this.containerComponent.bookmarkedCount; //getting error here reading the value of bookmarkedCount
}
试试这样 -
export class AppComponent {
bookmarkedCount: any;
constructor(private containerComponentComponent: ContainerComponentComponent){
this.bookmarkedCount = this.containerComponentComponent.bookmarkedCount;
}
}
我想你在这里以正确的方式做到了
但有时在孩子被渲染之前会调用ngAfterViewInit()
。我们通常使用ngOnInit()
进行这种绑定。
所以尝试这样..
@ViewChild(ContainerComponent) private containerComponent:ContainerComponent;
ngOnInit() {
this.count = this.containerComponent.bookmarkedCount;
}
我希望这能解决你的问题:)
没有找到任何更容易的替代解决方案。因此,我创建了一个共享服务,以获取app组件中的bookmarkedCount的值,并在服务中的更改中更新它。每当我点击添加/删除书签时,我都在调用changeCount方法
//for bookmark count
private count:number;
private messageSource = new BehaviorSubject(this.count);
currentCount = this.messageSource.asObservable();
changeCount(count: number) {
if(count!=undefined)
this.messageSource.next(count);
}
在app.component.ts中 - >
updateCount(){
this.dataService.currentCount.subscribe(res => {
this.count = res;
});
return true;
}