【问题标题】:Unsubscribe to observable when navigating away from an onsen ui page离开温泉 ui 页面时取消订阅 observable
【发布时间】:2021-01-06 12:59:49
【问题描述】:

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

我遇到的问题是,当我订阅了 ons 页面中的 observable 并且用户导航离开该页面时,observable 仍然处于活动状态。使用温泉导航器更改页面时,似乎没有调用 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.');
  }

}

【问题讨论】:

  • 请注意 onsen-ui,但要取消订阅,您需要维护对订阅的引用并将其处理:this.subscriptions.push(this.menuService.changePage$.subscribe(...));ngOnDestroythis.subscriptions.forEach(subscription => subscription.unsubscribe());
  • @AluanHaddad true 但这并不能真正解决 ngOnDestroy 未被调用的问题
  • link@Kevin Shiflett 和,请参考这里
  • 你能分享一下我们正在设置登录选择器的html组件吗?

标签: angular typescript onsen-ui angular2-observables rxjs-observables


【解决方案1】:

如果组件不会被销毁,那么您可能需要考虑其他方法,例如订阅路由器更改并取消订阅您的订阅者。
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.*/
    })
  }

希望这有帮助,快乐编码

【讨论】:

  • 我不认为ons-navigator 使用正常的角度路由
【解决方案2】:

这似乎是 OnsNavigator 的正常行为。如果您想在页面被推送后取消订阅 observable,您可以在 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());
    });
  }

}

【讨论】:

    猜你喜欢
    • 2020-08-29
    • 1970-01-01
    • 1970-01-01
    • 2019-01-20
    • 1970-01-01
    • 2019-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多