目前正在学习 RxJS。我有一个整数selectedCourseIndex
在我想要订阅一个单独的组件的服务中。
课程部分.service.ts
private selectedCourseIndex: number = -1; //this number can change from another method
private selectedCourseIndexUpdated = new Subject<number>();
getSelectedCourseUpdateListener(){
return this.selectedCourseIndexUpdated.asObservable();
}
课程部分.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
});
}
但是,订阅永远不会触发,无论是在最初订阅时还是在整数更改时。怎么了?
“Subject”可观察对象不会在订阅时重放之前的值。仅当您[以某种方式]在服务中执行以下操作时,您的订阅才会触发 -
this.selectedCourseIndexUpdated.next(<your new number>);
要在每个订阅上触发订阅[以获取最后发出的值],您应该使用“BehaviorSubject”而不是像这样的主题 -
private selectedCourseIndexUpdated = new BehaviorSubject<number>(0);
BehaviorSubject 重放每个订阅上最后发出的值。请注意,BehaviorSubject 构造函数采用默认值。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)