在 angular 4 中更改路线时自动保存 form/model 内容

Autosave the form/model content on route change in angular 4

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

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

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

您在离开时保持订阅处于打开状态,因此它会递增。您需要取消订阅:

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();
}