使用主题发布

using publish with subject

目标是有一个服务,2个组件依赖服务。更新将在外部触发,所有依赖服务数据的组件都将收到新数据可用的通知。为此,我使用了一个类型化的主题,然后将其作为可连接的可观察对象发布。

在调试器中查看让我困扰的一件事是引用计数保持为 0,但我不确定我是否误解了它们的含义。任何有关预期结果以及如何解决此问题的信息都很棒。

每个组件都有相同的代码

  ngOnInit() {
    this.stepService.stepsFeed.subscribe(val => {
      console.log(`Got Steps in operations`);
      this.availableOperations = val;
    });
    console.log(`subscribed`);
  }

服务有以下内容

constructor(
    private http: HttpClient) {

    this.stepsSubject = new Subject<StepDefinition[]>();
    this.stepsFeed = this.stepsSubject.pipe(
      tap(_ => {
        this.log('new steps published');
      }),
      publish()
    ) as ConnectableObservable<StepDefinition[]>;

    this.getStepDefinitions()
      .subscribe(operations => {
        this.stepsFeed.connect();
        this.log('connected');
      });
  }

  private stepsUrl = 'api/steps';

  private stepsSubject: Subject<StepDefinition[]>;
  public stepsFeed: ConnectableObservable<StepDefinition[]>;

  private getStepDefinitions(): Observable<StepDefinition[]> {
    return this.http.get<StepDefinition[]>(this.stepsUrl)
      .pipe(
        tap(steps =>
        {
          this.stepsSubject.next(steps);
          this.log('fetched steps');
        }),
        catchError(this.handleError('getStepDefinitions', []))
      );
  }

输出结果如下:

subscribed
subscribed
fetched steps
connected

解决方法:

const subscribe = example.subscribe(val => console.log(val));
const subscribeTwo = example.subscribe(val => console.log(val));

//share observable among subscribers
const sharedExample = example.pipe(share());