问题可能是由于路由器导致 Akita 状态被清除导致的。要解决此问题,请确保使用 Angular Router(不是 Akita Router),然后使用以下代码:
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { untilDestroyed } from 'ngx-take-until-destroy';
import { MyStore } from './my-store.service';
@Component({
selector: 'app-root',
template: `
{{ store.query.getActive().name }}
`
})
export class AppComponent implements OnInit {
constructor(private router: Router, public store: MyStore) {}
ngOnInit() {
this.router.events.pipe(untilDestroyed(this)).subscribe((event) => {
this.store.reset();
});
}
navigate(url: string) {
this.router.navigateByUrl(url);
}
}
在此示例中,MyStore
是一个 Akita Store,getActive()
是查询上的选择器。在 reset()
函数内,重置所有状态和活动实例,以避免在导航到不同页时数据重新启动。此外,使用 ngx-take-until-destroy
进行习惯性的取消订阅。
记得导入所有必要的包,以及使用 untilDestroyed
来进行自动清理,以避免内存泄漏。