订阅RxJ中的现有observable

时间:2017-05-11 14:11:12

标签: rxjs angular2-services rxjs5

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

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

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

    }
  }

}

任何帮助?

1 个答案:

答案 0 :(得分:1)

试试这个:

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