离子3 NGRX - 状态变化的订阅功能在单个状态变化时多次调用

问题描述 投票:0回答:1

我有一个离子3应用程序,我正在使用NGRX来跟踪状态。我的应用程序通过BLE连接到设备。

在我的连接页面(连接到BLE设备)中,我有以下内容:

 private connectionStateChangedCount: number;

  constructor(public navCtrl: NavController,
              public navParams: NavParams,
              private device: DeviceActionsDispatcherProvider) {
    this. connectionStateChangedCount = 0;
    console.log('CONNECTION - constructor ' + this. connectionStateChangedCount);
    store.select(s => s.connection).subscribe(this.connectionStateChanged.bind(this));
  }

  //  I only want this.device.onConnection() called ONCE when the deviceConnectionState is “connected
  connectionStateChanged(connectionStore: any) {  
    if (connectionStore.deviceConnectionState === 'connected' && 
        this. connectionStateChangedCount === 0) {
      this.connectionStateChangedCount = this. connectionStateChangedCount + 1;
      console.log('CONNECTION – connectionStateChanged  ' + this. connectionStateChangedCount);
      this.device.onConnection();
    } 
  }

我偶尔看到的是(在chrome:// inspect):

connection.ts:67  CONNECTION – connectionStateChanged 1 
connection.ts:67 'CONNECTION – connectionStateChanged 1

我不确定这是怎么回事? 'CONNECTION - connectionStateChangedCount正在递增,但订阅函数connectionStateChanged被调用两次,两个案例中connectionStateChangedCount为1 - 背靠背?

我还尝试用if语句中的unsubscribe替换变量connectionStateChangedCount来“try”并阻止对this.device.onConnection()的额外调用。这也是不成功的,偶尔我会接到两个电话。

其他一些说明:

  1. 发生这种情况时,我没有看到对连接页面构造函数的多次调用。
  2. 当我从app.component.ts中的BLE设备 - this.nav.setRoot(ConnectionPage)断开连接并尝试连接到ConnectionPage(它是根目录)上的BLE设备时,它会显示出来。

关于为什么会发生这种情况的任何想法都会很棒。

typescript ionic3 ngrx ngrx-store
1个回答
0
投票

事实证明,问题是当我从一个页面转到另一个页面时,NGRX订阅商店仍然存在。当我从另一个页面返回到连接页面时,它将再次重新订阅该商店,导致connectionStateChanged触发两次。

在离开连接页面之前,我现在取消订阅ionViewWillLeave()中的商店。

这已经解决了我的问题。

© www.soinside.com 2019 - 2024. All rights reserved.