【发布时间】:2019-06-05 23:51:47
【问题描述】:
目前正在学习 RxJS。我在一个服务中有一个整数selectedCourseIndex,我想要一个单独的组件来订阅。
courses-section.service.ts
private selectedCourseIndex: number = -1; //this number can change from another method
private selectedCourseIndexUpdated = new Subject<number>();
getSelectedCourseUpdateListener(){
return this.selectedCourseIndexUpdated.asObservable();
}
courses-section.component.ts
private selectedCourseIndex: number = -1; //Placeholder initial selectedCourseIndex until new one given on init from courses-section service
private selectedCourseSub: Subscription;
constructor( public coursesSectionService: CoursesSectionService ){}
ngOnInit(){
this.selectedCourseIndex =
this.coursesSectionService.getSelectedCourseIndex();
this.selectedCourseSub = this.coursesSectionService
.getSelectedCourseUpdateListener()
.subscribe((selectedCourseIndex: number) => {
this.selectedCourseIndex = selectedCourseIndex;
console.log('this fires when subscription updates'); //this never fires once
});
}
但是,无论是在最初订阅时还是在整数更改时,订阅都不会触发。怎么了?
【问题讨论】: