我有以下对象:
class Question { idQuestion: string; question: string; typeQuestion: string; } class Answer { idAnswer: string; idQuestion: string; answer: string; } class Option { idOption: string; idQuestion: string; option; }
我想填充以下对象:
class QuestionOptionsAnswer { question: Question; answer: Answer; options: Option[]; }
现在,我为每种对象提供服务,因此我们可以通过以下方式对其进行说明:
questionService.getQuestions(); answerService.getAnswers(); optionService.getOptions();
要填充一个questionoptionsanswer对象,我已经做了嵌套请求:
questionService.getQuestions() .subscribe( answerService.getAnswers() .subscribe( optionService.getOptions() .subscribe(); ) )
我可以正确填充questionoptionsanswer对象,但速度很慢,所以我认为我做的很糟糕.有一个questionoptionsanswer背后的想法是用一个简单的方式渲染带有angular2指令的html.
我读了关于flatMap,switchMap,forkJoin但我不太确定如何使用它们.
这可能是加载这些数据的好方法吗?
questionoptionsanswer将有一个问题对象,与之相关的答案,以及可能的选项,具体取决于类型问题,即:选择,无线电,多个等.
因此,您需要调用第一个请求并等待其响应,然后同时调用另外两个请求(对于选项和答案).
由于我想知道两个响应何时准备就绪,我将使用Observable.forkJoin()
运算符,它们在完成时发出包含源Observables的所有值的单个数组,然后将数据添加到我将在订阅时传递给Observer的qoa变量.
像concat()或concatMap()这样的运算符可以按顺序进行多个HTTP调用,但是当你需要创建多个Observable来构造一个你要发出的大响应时(在你的情况下是QuestionOptionsAnswer),它们不是很有用.
我还使用Observable.of(…)来模拟HTTP请求.我不知道你的用法是什么,所以你可能不会使用Observable.create()并使用Subject代替:
function getQOA() { return Observable.create(observer => { Observable.of({ question_id: '1' }).subscribe(response => { var qoa = new QuestionOptionsAnswer(); let question = new Question(); question.idQuestion = response.question_id; qoa.question = question; let obs1 = Observable.of({ answer_id: '1',answer: 'bla' }); let obs2 = Observable.of([{ option_id: '1',option: 'ble' }]); Observable.forkJoin(obs1,obs2).subscribe(responses => { let [answerResponse,optionsResponse] = responses; let answer = new Answer(); answer.idAnswer = answerResponse.answer_id; answer.answer = answerResponse.answer; qoa.answer = answer; qoa.options = optionsResponse.map(o => { let option = new Option(); option.idOption = o.option_id; option.option = o.option; return option; }); observer.next(qoa); }); }); }); } getQOA().subscribe(qoa => console.log(qoa));
打印到控制台:
QuestionOptionsAnswer { question: Question { idQuestion: '1' },answer: Answer { idAnswer: '1',answer: 'bla' },options: [ Option { idOption: '1',option: 'ble' } ] }