RxJS 订阅未触发 [英] RxJS subscription not firing

查看:40
本文介绍了RxJS 订阅未触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前正在学习 RxJS.我在一个服务中有一个整数 selectedCourseIndex,我想订阅一个单独的组件.

Currently learning RxJS. I have an integer selectedCourseIndex within a service that I'd like a separate component to subscribe to.

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
    });
  }

但是,订阅永远不会触发,无论是在最初订阅时还是在整数更改时.怎么了?

However, the subscription never fires, either when it initally subscribes or when the integer changes. Whats wrong?

推荐答案

"Subject" observable 不会在订阅时重放之前的值.只有在您的服务中[以某种方式] 执行以下操作时,您的订阅才会触发 -

"Subject" observable does not replay the previous values on subscribe. Your subscription will only fire if you do the following in your service [somehow] -

this.selectedCourseIndexUpdated.next(<your new number>);

要在每次订阅时触发订阅[获取最后发出的值],您应该使用BehaviorSubject"而不是像 -

To fire subscription on each subscribe [to get the last emitted value] you should use "BehaviorSubject" instead of Subject like -

private selectedCourseIndexUpdated = new BehaviorSubject<number>(0);

BehaviorSubject 在每个订阅上重放最后发出的值.注意 BehaviorSubject 构造函数采用默认值.

BehaviorSubject replay the last emitted value on each subscription. Notice BehaviorSubject constructor takes the default value.

这篇关于RxJS 订阅未触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆