繁体   English   中英

rxJS observable 无法订阅

[英]rxJS observable not reaching subscribe

我使用 Angular 2 和 RxJS,我很难设置一个简单的 observables 系统。

据我了解,运算符 do 用于副作用,您将代码放置在 susbcribe() 函数中处理 observable 返回的结果。

所以我的组件要求服务初始化系统。 该服务对服务器进行 2 个 http 调用,并将它们组合在一个流中,以便组件订阅并确保一切准备就绪。 服务中的 2 个 http 调用之一是从服务器检索固定数量的结果,然后根据需要将这些结果提供给组件。 因此,当 Service 发现它需要更多数据时,它会再次调用服务器。

这不起作用,因为我认为我需要先取消订阅原始 http 调用,然后再进行新调用(这是真的吗?)。

所以这就是我所得到的......这是行不通的,因为它没有在 getQuestions 方法中订阅。

在组件中

ngOnInit() {
    // show spinner

    this.gamesService
      .initializeGame()
      .subscribe(data => {
        console.log('Game initialized');
        // remove spinner
      });
  }

在服务中

initializeGame(opponent_id: string): Observable<any> {
    return Observable
      .forkJoin([this.getQuestions(), this.newGame()]);
  }

  getQuestions(): Observable<any> {
    // composes postData with POST parameters

    this.questionsObservable = this.authHttp
      .post(this.settings.authApiUrl, postData)
      .map((response: Response) => response.json());

    this.questionsObservable
      .subscribe(data => {
        // save data in the service, which will be consumed
      })
      .unsubscribe(); // do I need to unsubscribe?

    return this.questionsObservable;
  }

  getQuestion(category: string): any {
    // consume question by Component
    if (no_more_questions_in_service) this.getQuestions();
    return question;
  }

所以,这现在正在起作用。 为什么没有达到订阅方法?

有没有更好的方法来实现这一目标? 谢谢

好的,我意识到(也感谢@martin)我在时间之前退订了。

我设法得到了我想要的东西,以防万一有人想使用它。

现在的服务是这样的:

initializeGame(opponent_id: string): Observable<any> {
    return Observable
      .forkJoin([this.getQuestions(), this.newGame()]);
  }

  getQuestions(): Observable<any> {
    // postData

    return this.authHttp
      .post(this.settings.authApiUrl, postData)
      .map((response: Response) => response.json())
      .do(data => save_data);
  }

  private getQuestionsByCategory(category: string) {
    // postData

    this.authHttp
      .post(this.settings.authApiUrl, postData)
      .map((response: Response) => response.json())
      .subscribe(data => save_data
  }

  getQuestion(category: string): any {
    // consume question by Component
    if (no_more_questions_in_service)
      this.getQuestionsByCategory(category);
    }
    return question;
  }

所以我现在有两种不同的方法; 我不需要取消订阅(我认为),现在似乎运行良好。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM