订阅 RxJs 中现有的可观察对象

Subscribing to existing observable in RxJs

我的 angular 服务 returns 可观察。但是,每当我订阅它时,它都会被重新调用。在此特定示例中,您可以看到获取用户的请求被发送了 10 次,而不是一次发送给多个观察者。

预期行为:创建可观察对象并订阅它。只发送一个请求,所有订阅都收到相同的值。

@Injectable()
class ExampleService {
  constructor(private http: Http) { }
  read() {
    return this.http.get('https://api.github.com/users');
  }
}

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>

      <button (click)='test()'>Test</button>
    </div>
  `,
})
export class App {
  name:string;
  subscription: Observable<any>;

  constructor(private exampleService: ExampleService) {
    this.name = `Angular! v${VERSION.full}`
  }

  test() {
    for (let x = 0; x < 10; x++) {
      if (this.subscription) {
        console.log('Using existing subscription');

        this.subscription.subscribe(
          response => {
            console.log('From another')
          })
      } else {
        this.subscription = this.exampleService.read();
        this.subscription.subscribe(
          response => {
            console.log('From originalSubscription');
            this.subscription = null;
          });
      }

    }
  }

}

有什么帮助吗?

试试这个:

@Injectable()
class ExampleService {
  constructor(private http: Http) { }
  read() {
    return this.http.get('https://api.github.com/users').publishReplay().refCount();
  }
}