如何将对象传递给 rxjs subscribe() 回调函数?

how to pass object to rxjs subscribe() callback function?

我正在开发一个 Ionic2 应用程序,使用 cordova-plugin-network-information,我正在从我的 app.ts 订阅连接和断开事件,并希望能够传递对我的 NavController 的引用和一个 Loading 组件到 subscribe() 回调中,所以每当断开连接事件触发时,我可以在 UI 之上向用户呈现一个 Loading 覆盖层。我看到在回调中,对 "this" 对象的引用更改为一个名为 "SafeSubscriber" 的对象,我认为这是为其 Observer 对象键入 class 的 rxjs,我在这里遇到的问题是我无法使用 Chrome DevTools 将 app.ts 中的这些实例提供给回调中的此代码 我也无法找到离开此上下文的方式以访问应用程序对象本身。

这是我的代码:

    ngOnInit()
    {
      // Nav Controller:
      this.nav = <NavController>this.app.getComponent('nav');

      // Disconnect Detection
      let disconnectSubscription = Network.onDisconnect().subscribe(() =>
      {
          console.log('Disconnect Detected');
          // Push Loading into nav stack here...!
          // this.nav.present(this.loading);  <- no this object...
      });
    }

这是我在 Chrome DevTools 中查询 'this' 对象时得到的结果(这应该将其原始上下文保留在 lambda [粗箭头] 函数中,对吗?)

我尝试在订阅之前设置一个 "that" 对象,这样变量 "this" 就不会干扰回调 "this" 范围,它在在这种情况下,因为 'that' 在 subscribe() 之前立即声明(假设:any = this;)在触发断开连接事件时在回调内部未定义。

我知道这不是放置直接更改 UI 的代码的最佳位置,但我看不到其他地方,因为我在这里需要的是一个全局事件处理程序,它通过设置此覆盖来工作每当未检测到连接且用户正在查看应用程序中的某些页面时。

我认为应该有一个非常简单和优雅的解决方案,但我似乎无法找到它。有没有办法将参数传递给 subscribe() 函数?某种带有我需要的引用的对象?

提前致谢。

我很确定简单的闭包应该可以解决问题。试试这个:

ngOnInit()
    {
      // Nav Controller:
     var nav = <NavController>this.app.getComponent('nav');

      // Disconnect Detection
      let disconnectSubscription = Network.onDisconnect().subscribe(() =>
      {
          console.log('Disconnect Detected');          
          nav.present(true);  
      });
    }

我运行遇到了同样的问题。我也在我的项目中得到 SafeSubscriber。但是,当我尝试为其创建 Plunker 时,我无法重现该问题。也就是说,附加的 plunker 确实证明了粗箭头 + this 的行为符合预期。所以你应该不需要做任何that = this风格的解决方法。

要在订阅中传递组件变量对象,您必须使用更多 rxjs 运算符,例如 combineLatest。只需创建一个新的 Observable 对象,你想在 subscribe 中传递它,并将其作为 combineLatest 的参数。 例如

    // Note: The **of** here is the rxjs of operator to create the observable. 
    combineLatest(
         [
            of(the object you want to pass{Here you will have the this variable}), 
            your API call
         ])
        .pipe(take(1),)
        .subscribe(([yourObject, apiResponse]) => {
            console.log(yourObject + " " + apiResponse);
         });

这是 我找到的最终答案。

Karan 的模式奏效了,但这个也奏效了,这有点简单(使用绑定):

    ngOnInit()
    {
      // Nav Controller:
      this.nav = <NavController>this.app.getComponent('nav');

      // Disconnect Detection
      const fn = (() => {
          console.log('Disconnect Detected');
          this.nav.present(this.loading); // 'this' should be set right
      }).bind(this);
      let disconnectSubscription = Network.onDisconnect().subscribe(fn);
    }

不是 运行 它,但是我的代码同样适用,它遵循相同的模式并且具有与 op 描述的相同的错误。使用闭包不起作用,我不明白为什么。调用者 'SafeSubscriber' 使用调用方法并将上下文设置为自身作为该调用的一部分。