我试图使用app.component.ts中的view child来获取模块组件中存在的property(bookmarkedCount)值到app组件中,但是在读取app组件中的属性值时出现错误,未定义。为什么会这样呢?
错误TypeError:无法读取未定义的属性'bookmarkedCount' 在AppComponent.push ../ 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
}
答案 0 :(得分:0)
尝试这样-
export class AppComponent {
bookmarkedCount: any;
constructor(private containerComponentComponent: ContainerComponentComponent){
this.bookmarkedCount = this.containerComponentComponent.bookmarkedCount;
}
}
请参阅details here
答案 1 :(得分:0)
我认为您在这里以正确的方式进行操作
,但有时会在渲染孩子之前调用 ngAfterViewInit()
。我们通常将 ngOnInit()
用于这种绑定。
所以尝试这样。.
@ViewChild(ContainerComponent) private containerComponent:ContainerComponent;
ngOnInit() {
this.count = this.containerComponent.bookmarkedCount;
}
我希望这能解决您的问题:)
答案 2 :(得分:0)
没有找到任何更简单的替代解决方案。所以最后我创建了一个共享服务来获取app组件中bookmarkedCount的值并在服务中的更改时对其进行更新。这里我每次添加/删除书签时都会调用changeCount方法点击
#set( $stringMap = '[{"ace":"clubs"}]' )
#set( $myMap = {} )
#set( $eval = '#set($list = ' + $stringMap + ') #set ($myMap.ace =
$list.get(0).ace)' )
#evaluate( $eval )
$myMap.ace ## prints 'clubs'
在app.component.ts->
中 //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);
}