简体   繁体   English

正确使用带有RXJS6和DWR的bindCallback

[英]Properly using bindCallback with RXJS6 and DWR

I'm currently using bindCallback the following (now deprecated) way: 我目前bindCallback以以下方式(现已不推荐使用)使用bindCallback

const someMapping = (data) => { return { ... }};

public someCall(id) {
  // Foo.someFunction is function with callbacks
  return this.toObservable(Foo.someFunction, someMapping, id);
}

private toObservable(func, mappingFunction, ...args: any[]) {
  return bindCallback(func, mappingFunction)(...args);
} 

Other than this being deprecated, I have another issue. 除了不推荐使用之外,我还有另一个问题。 If I call the someFunction manually: 如果我手动调用someFunction

var callFn = function(data) {...}
var warnFn = function(data) {...}
var errFn = function(data) {...}
Foo.someFunction(id, {callback: callFn, warningHandler: warnFn, errorHandler: errFn})

It will throw success, warnings and errors correctly. 它将正确引发成功,警告和错误。 I didn't create this DWR callback function (there are many of them), and I can't change them. 我没有创建此DWR回调函数(有很多),并且无法更改它们。 Documentation isn't helping enough. 文档的帮助不足。

How can I modify this to handle all three (success, warning, error) callbacks and return as observables? 如何修改它以处理所有三个(成功,警告,错误)回调并以可观察的形式返回? Warning and error can both throw an error. 警告和错误都可能引发错误。

The best option is to create your own observable. 最好的选择是创建自己的可观察对象。

public someCall(id) {
  return new Observable(observer => {
                         Foo.someFunction(id,
                           {
                            callback: value => {
                                                 observer.next(value);
                                                 observer.complete();
                                               },
                            warningHandler: warn => observer.error(warn),
                            errorHandler: error => observer.error(error)
                          });

                        });

It's similar to calling someFunction manually but emits to a stream. 它类似于手动调用someFunction ,但是会发出流。

From bindCallback documentation bindCallback文档

The input is a function func with some parameters, the last parameter must be a callback function that func calls when it is done. 输入是带有某些参数的函数func,最后一个参数必须是func完成后调用的回调函数。

If I understand correctly your code 如果我正确理解您的代码

bindCallback(func, mappingFunction)

func is actually Foo.someFunction . func实际上是Foo.someFunction

If I look at Foo.someFunction this is not a function with a callback function as its last parameter, as it is required by bindCallback . 如果我看Foo.someFunction它不是将回调函数作为最后一个参数的函数,因为bindCallback要求它。

So I am wondering if this code has ever worked. 所以我想知道这段代码是否曾经奏效。

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

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