我有一个离子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()的额外调用。这也是不成功的,偶尔我会接到两个电话。
其他一些说明:
关于为什么会发生这种情况的任何想法都会很棒。
事实证明,问题是当我从一个页面转到另一个页面时,NGRX订阅商店仍然存在。当我从另一个页面返回到连接页面时,它将再次重新订阅该商店,导致connectionStateChanged触发两次。
在离开连接页面之前,我现在取消订阅ionViewWillLeave()中的商店。
这已经解决了我的问题。