【问题标题】:Autosave the form/model content on route change in angular 4在角度 4 中自动保存路径更改时的表单/模型内容
【发布时间】:2018-07-12 15:05:44
【问题描述】:

在 Angular 4 应用程序中,我正在从一个模块移动到另一个模块,我想自动保存我的内容,因此我需要识别路线的变化。

class MyClass {
  constructor(private router: Router) {
    router.events.subscribe((val) => {
        // see also 
        console.log(val instanceof NavigationEnd) 
    });
  }
}

我已使用此代码,但每次访问时此调用都会增加。 它类似于 Gmail 撰写当我从撰写屏幕移动到其他屏幕时它如何将数据保存到草稿。

【问题讨论】:

  • 实际期望是什么?您正在订阅这些事件,因此每个路由事件的每个订阅都会为单个路由触发 7 次
  • this.sub = router.events.subscribe((val) => { // 另见 if (val instanceof NavigationStart) { // 隐藏加载指示器 alert('compose'); } // this.memoformatSubmit(false); });我用这个现在可以工作了
  • 好的。很高兴它的工作原理!

标签: angular angular4-router


【解决方案1】:

您在离开时使订阅保持打开状态,因此它会增加。您需要退订:

import { Subscription } from 'rxjs/Subscription';

// ...

sub = new Subscription();

// ...

this.sub = router.events.subscribe((val) => {
    // see also 
    console.log(val instanceof NavigationEnd) 

});

// ...

ngOnDestroy() {
  this.sub.unsubscribe();
}

【讨论】:

    猜你喜欢
    • 2020-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多