简体   繁体   English

RxJS在事件上发送多个唯一的ajax请求

[英]RxJS sending multiple unique ajax requests on event

If I have an event type; 如果我有一个事件类型; say a click event. 说一个点击事件。 That I want to fire 3 unique ajax requests for but I want to subscribe to the final result of all 3 requests 我想触发3个唯一的Ajax请求,但我想订阅所有3个请求的最终结果

What is the proper design pattern for this sequence. 此序列的正确设计模式是什么?

My current code block looks something like this 我当前的代码块看起来像这样

$rootScope.$eventToObservable('selectUser')
    .throttle(500)
    .map(data => {
        return angular.copy(data.additionalArguments[0].entity);
    })
    .select(d => {
        return {
            Member: MemberService.getMember(d.ID),
            otherData: MemberService.dataOtherData(d.ID),
            Notes: MemberService.getNotes(d.ID),
            Log: MemberService.getLog(d.ID)
        }
    })
    .switchLatest() //Code current dies here with an object is not a function error. I believe because the return object is not an obserable. But not sure what the proper design pattern is.
    .subscribe(model => {
        //I would like that model would contain an object with the result of the 3 responses above.
        $scope.model = model;
});

You can use zip to synchronize your requests. 您可以使用zip来同步您的请求。 zip will cause all observables to be subscribed, and yield each time all of those observables fire. zip将导致所有可观察对象都被订阅,并在每次触发所有这些可观察对象时产生。 So, once the n th item from each observable is yielded, zip will yield it's n th value, which is created by using the n th values from the original observables. 因此,一旦产生了每个可观察对象的第n个项目,zip就会产生它的第n个值,该值是使用原始可观察对象的第n个值创建的。

Once you have that, can you use switchLatest , which works on Observable<Observable<T>> , and makes sure it's always subscribed to the latest observable. 一旦有了,就可以使用在Observable<Observable<T>>上运行的switchLatest ,并确保它始终订阅最新的observable。 So, if you select a new user, it'll just unsubscribe from any pending request, and subscribe to the next one instead. 因此,如果您选择一个新用户,它只会取消订阅任何待处理的请求,然后订阅下一个请求。

$rootScope.$eventToObservable('selectUser')
    .throttle(500)
    .map(data => {
        return angular.copy(data.additionalArguments[0].entity);
    })
    .map(entityToExpandedData).switchLatest()
    .subscribe(model => {
        $scope.model = model;
    });

function entityToExpandedData (entity) {
    return Rx.Observable
        .zip(
            MemberService.getMember(d.ID),
            MemberService.dataOtherData(d.ID),
            MemberService.getNotes(d.ID),
            MemberService.getLog(d.ID),
            makeExpandedData
        );
}

function makeExpandedData (member, otherData, notes, log) {
    return {
        member:     member,
        otherData:  otherData,
        notes:      notes,
        log:        log
    };
}

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

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