内部可观察量的角动态数

时间:2017-12-28 13:33:36

标签: angular rxjs

我有一个Angular 5服务,我希望有一个可观察到的动态数据,让我们调用它们,来电者。注入此服务的任何组件都可以获得一个观察者/主题/任何内容,使用它来呈现自己" on"或者"关闭" (真/假,无论如何),完成后,完成。它可以多次这样做。

我的服务还应该公开一个BehaviorSubject,它传递所有这些值。我该怎么办呢?例如:

@Injectable() class MyService {
  results$: BehaviorSubject<any> = new BehaviorSubject<any>(true);
  callers: any[] = [];

  getSubject() {
    const subject = new Subject();
    callers.push(subject);
    // TODO: Now what? How to tell result$ to listen to this new one too?
    subject.finally(() = {
      // TODO: Now what? How to kick it out of the array when complete, and tell results$?
    });

    return subject;
}

编辑每条评论请求,例如,典型的消费者可以这样做:

@Component({
  selector: 'my-comp',
  template: '<button (click)="doWork()">Do work</button>'
})
export class MyComponent {
  constructor(private myService: MyService,
              private otherService: OtherService
  ) {}

  doWork() {
    // grab the semaphore instance
    const semaphore = myService.getSubject();
    // Kick off the semaphore and start some async activity (http call in my case)
    semafore.next('on');
    otherService.doAnotherWork()
      .subscribe(() => semaphore.complete());
  }
}

正如您所看到的,其他服务可以做两件事情:

  1. 随时启动此信号量。
  2. 立即启动多个。
  3. 我可以在页面上同时拥有多个此类消费者。

    (现在我想到了这一点,我可能应该考虑一些清理逻辑,例如用户在中途处理时导航。)

0 个答案:

没有答案
相关问题