等到一个订阅完成

时间:2017-05-01 15:43:48

标签: angular observable

你能告诉我如何等待一个订阅完成吗?

注意:我需要等到这个let survey = this.getSurveys(currentQuestionCode)完成。之后应该执行return this.question = value;。这里的项目来自JSON数组。

更新:我的问题与上述重复问题不同。这里的问题是如何等到第二个observable完成其工作。

page.ts

 getQuestions(currentQuestionCode: string): any {
    this.surveyData.getQuestions().subscribe(
      result => {

        _.forEach(result, (value, key) => {

          if (key == currentQuestionCode) {
            let survey = this.getSurveys(currentQuestionCode);//here is the issue
            return this.question = value;
          }
        });
      },
      err => { },
      () => { }
    );
  }

  getSurveys(currentQuestionCode: string): any {
    this.surveyData.getSurveys().subscribe(
      result => {

        _.forEach(result, (value, key) => {

          if (key == currentQuestionCode) {
            return this.survey = value;
          }
        });
      },
      err => { },
      () => { }
    );
  }

Service.ts

 //get Questions
  getQuestions(): Observable<any> {
    return this.http.get("/assets/data/questions.json")
      .map(this.extractData)
      .catch(this.handleError);

  }

  //get Surveys
  getSurveys(): Observable<any> {
    return this.http.get("/assets/data/survey.json")
      .map(this.extractData)
      .catch(this.handleError);

  }

1 个答案:

答案 0 :(得分:0)

Rxjs有Observable方法来处理这个问题。

getBoth(){
   return getQuestions()
      .combineLatest(getSurveys())
      .map(([q, s]) => {
         return `${q} ${s}`;
      });
}
...

getBoth().subscribe(...);