0

I have a ionic2 app with ngrx/store implemented and i'm encountering a strange behaviour.

nav:Subscription;

ngOnInit(): void {
    this.nav = this.store.select(fromRoot.getLoginState).subscribe(res => {
        if(res){
            this.navCtrl.setRoot(TabsPage);
        }
    })
}

ngOnDestroy(): void {
    this.nav.unsubscribe()
}

store.select(fromRoot.getLoginState) returns a boolean and if it's true I want to set TabsPage as root in Ionic 2. Obviously I only want it to happen once so I unsubscribe in the onDestroy lifecycle hook.

However the unsubscription doesn't seem to work and each time i get a state change it set the view back to Tabspage (so the subscription still fires)

Any ideas?

Cheers

4

2 回答 2

1

您应该在订阅中取消订阅它

this.nav = this.store.select(fromRoot.getLoginState).subscribe(res => {
        if(res){
            this.navCtrl.setRoot(TabsPage);
        }
        //condition to check the required data is available 
         this.nav.unsubscribe();
}
于 2017-03-25T07:29:41.563 回答
0

ngrx使用s,当您不在乎能够在收到结果之前取消订阅时rxjs Observable,可以轻松地将其转换为s 以接收这样的单个值。Promise

如果您真的只想要一个值并且不会监视商店的登录状态更新,那么Observable.toPromise比搞乱订阅更容易,并且使代码的意图更清晰恕我直言。

这是您使用的示例toPromise

// notice no assignment here, since no need to unsubscribe
this.store.select(fromRoot.getLoginState).toPromise()
    .then(res => res && this.navCtrl.setRoot(TabsPage));
于 2017-05-04T22:29:01.437 回答