离开温泉用户界面页面时退订可观察

问题描述

我有一个运行onsen ui的Angular 2+应用程序,已经将某些组件设置为页面,并且正在使用ons-navigator在它们之间进行切换。

即时消息存在的问题是,当即时消息在ons页面订阅一个可观察对象并且用户导航离开该页面时,该可观察对象仍然处于活动状态。使用Onsen导航器更改页面时,似乎没有调用ngOndestroy。

我想知道如何解决这个问题?

这里是一些代码

import { Component,OnDestroy,OnInit } from '@angular/core';
import { OnsNavigator } from 'ngx-onsenui';
import { HomePageComponent } from '../home-page/home-page.component';
import { CommonDataService } from '../_services/common-data.service';
import { MenuService } from '../_services/menu.service';
import { UserService } from '../_services/user.service';

@Component({
  selector: 'ons-page',templateUrl: './login-page.component.html',styleUrls: ['./login-page.component.scss']
})
export class LoginPageComponent implements OnInit {

  constructor(
    private menuService: MenuService,private commonDataService: CommonDataService,private _navigator: OnsNavigator,private userService: UserService) { }
  

  ngOnInit() {
    this.menuService.changePage$.subscribe((page) => {
      this._navigator.element.pushPage(page,{data: {hoge: "fuga"}});
    });
  }

  ngOnDestroy(): void {
    //doesnt work
    console.log('on destroy called.');
  }

}

解决方法

这似乎是OnsNavigator的正常行为。如果要在页面推送后取消从可观察对象的订阅,可以在promise pushPage之后执行此操作。背着Thakur的答案,看起来像这样。

export class LoginPageComponent implements OnInit  {
  subscription: Subscription;

  constructor(
    private menuService: MenuService,private commonDataService: CommonDataService,private _navigator: OnsNavigator,private userService: UserService) { }
  

  ngOnInit() {
    this.subscription = this.menuService.changePage$;
    this.subscription.subscribe((page) => {
      this._navigator.element.pushPage(page,{data: {hoge: "fuga"}})
         .then(() => this.subscription.unsubscribe());
    });
  }

}
,

如果该组件不会被销毁,那么您可能必须考虑采用其他方法,例如订阅路由器更改并退订您的订户。
Reference Link

constructor(private router: Router) {
    router.changes.subscribe((val) => {
     /*Here console log the value you find something useful to add some logic
      to unsubscribe to your observers instead of ngOndestroy hook.*/
    })
  }

希望这会有所帮助,开心编码

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...