【发布时间】:2017-09-29 00:49:45
【问题描述】:
你能告诉我如何等到一个订阅完成吗?
注意:我需要等到这个let survey = this.getSurveys(currentQuestionCode) 完成。之后应该执行这个return this.question = value;。这里的项目是从 JSON 数组中获取的。
更新:我的问题与提到的重复问题不同。这里的问题是如何等到 2nd 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);
}
【问题讨论】:
-
@jonrsharpe 这不是我的问题。你能删除重复的吗?请允许其他人提供答案。我在这里需要帮助。
-
“我的问题不同” - 如何,具体来说?不要只是断言,解释。您似乎想返回数据;正如另一个问题所说,你不能那样做。如果您实际上从
getSurveys返回了 observable,您可以在getQuestions或.map/.flatMap中将.subscribe发送给它,进行一些转换等等,直到消耗数据的任何东西. -
你确定吗?因为您的代码实际上并没有从
getSurveys返回任何内容。内部回调中的return将允许forEach创建一个数组,但是不会去任何地方。相反,您可能需要再次从getSurveys返回一个可观察对象,以便getQuestions可以使用结果。我建议阅读 RxJS(另请参阅 stackoverflow.com/q/37304160/3001761,那里有很多信息),也许不要那么粗鲁。 -
另外,这段代码的目的是什么?要查找一个调查问题的调查回复?获取所有调查问题并遍历它们以找到您想要的问题似乎效率低下。最好向服务器请求您想要的一个调查问题。
标签: angular observable