在 rxjs 中执行高级 http 请求 [英] Performing advanced http requests in rxjs

查看:23
本文介绍了在 rxjs 中执行高级 http 请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下对象:

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[];
}

目前,我对每种对象都有一个服务,因此我们可以通过以下方式进行说明:

For now, I have a service for each kind of object, so we can illustrate it in the following way:

questionService.getQuestions();
answerService.getAnswers();
optionService.getOptions();

为了填充一个 questionoptionsanswer 对象,我做了嵌套请求:

To populate a questionoptionsanswer object I have doing nested requests:

questionService.getQuestions()
    .subscribe(
        answerService.getAnswers()
           .subscribe(
               optionService.getOptions()
                  .subscribe();
           )
    )

我可以正确填充 questionoptionsanswer 对象,但是速度很慢,所以我认为我的做法很糟糕.questionoptionsanswer 背后的想法是通过 angular2 指令以简单的方式呈现 html.

I can populate correctly the questionoptionsanswer object, but is is slow, so I think I am making a bad approach. The idea behind having a questionoptionsanswer is for rendering in a easy way the html with angular2 directives.

我读过flatMapswitchMapforkJoin,但我不太确定如何使用它们.

I read about flatMap, switchMap, forkJoin but I am not quite sure in how to use them.

哪个是加载这些数据的好方法?

Which could be a good approach to load this data?

questionoptionsanswer 将有一个问题对象,一个与之关联的答案,以及它可能的选项取决于 typeQuestion,即:select、radio、multiple 等.>

questionoptionsanswer will have a question object, an answer associated with it, and its possible options depending on the typeQuestion i.e: select, radio, multiple, etc.

推荐答案

因此您需要调用第一个请求并等待其响应,然后同时调用其他两个请求(用于选项和答案).

So you need to call the first request and wait for its response and then call the two other requests (for options and the answer) at the same time.

因为我想知道两个响应何时准备就绪,所以我将使用 Observable.forkJoin() 操作符,它在源 Observables 完成时发出一个包含所有值的单个数组,然后将数据添加到 qoa 订阅时我将传递给观察者的变量.

Since I want to know when both responses are ready I'll use Observable.forkJoin() operator that emits a single array with all values of source Observables when they completed and then add data to the qoa variable that I'll just pass to the Observer when it subscribes.

concat()concatMap() 等操作符可以很好地按顺序进行多个 HTTP 调用,但当您需要创建多个 Observable 以构建一个大型您想要发出的响应(在您的情况下为 QuestionOptionsAnswer).

Operators such concat() or concatMap() are good to make multiple HTTP calls in order but not very useful when you need to create multiple Observable to construct one large response you want to emit (QuestionOptionsAnswer in your case).

我还使用了 Observable.of(...) 来模拟 HTTP 请求.我不知道你的用例是什么,所以你可能不会使用 Observable.create() 而是使用 Subject :

I also used Observable.of(...) to simulate HTTP requests. I don't know what's your usecase so you'll maybe don't use Observable.create() and use Subject instead:

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' } ] }

这篇关于在 rxjs 中执行高级 http 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆