最佳答案
我试图从一个服务变量(isSidebarVisible
)中获取更新后的值,这个服务变量由另一个组件(header
)通过单击事件(toggleSidebar
)不断更新。
侧边栏,服务
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class SidebarService {
isSidebarVisible: boolean;
sidebarVisibilityChange: Subject<boolean> = new Subject<boolean>();
constructor() {
this.isSidebarVisible = false;
}
toggleSidebarVisibilty() {
this.isSidebarVisible = !this.isSidebarVisible
this.sidebarVisibilityChange.next(this.isSidebarVisible);
}
}
侧边栏组件
export class SidebarComponent implements OnInit {
asideVisible: boolean;
_asideSubscription: any;
constructor(private sidebarService: SidebarService) {
this.asideVisible = sidebarService.isSidebarVisible
this._asideSubscription = sidebarService.sidebarVisibilityChange.subscribe((value) => {
this.asideVisible = value
})
}
ngOnInit() {
}
}
Ts (更新服务变量的位置)
export class HeaderComponent implements OnInit {
isSidebarVisible: boolean;
_subscription: any;
constructor(private sidebarService: SidebarService) {
this._subscription = sidebarService.sidebarVisibilityChange.subscribe((value) => {
this.isSidebarVisible = value
})
}
toggleSidebar() {
this.sidebarService.toggleSidebarVisibilty()
}
ngOnInit() {
}
}
当 {{ isSidebarVisible }}
时,我可以看到 header.component.html
中的服务变量值发生了变化,但是在 sidebar.component.html
中,它总是打印默认值,而且从来不听这些变化。
请帮我解决这个问题。