使用主题发布

时间:2018-08-28 23:32:21

标签: angular rxjs rxjs6

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

在调试器中偷看的一件事是,我的引用计数保持为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

1 个答案:

答案 0 :(得分:1)

解决方法:

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