在Angular 14中,使用NGRX存储时,可能会遇到内存泄漏问题。在NGRX store中,订阅者必须显式取消订阅,否则它们将继续接收通知,即使它们不再使用存储。
以下是在Angular 14中正确使用NGRX存储的示例代码:
import { Component, OnDestroy } from '@angular/core'; import { Store } from '@ngrx/store'; import { AppState } from './app.state'; import { Subscription } from 'rxjs'; import { selectCounter } from './counter.selector';
@Component({ selector: 'app-counter', template: '
constructor(private store: Store
ngOnDestroy() { this.counterSubscription.unsubscribe(); } }
在该代码中,我们定义了一个名为“counterSubscription”的订阅变量,然后在组件构造函数中订阅选择器。最后,在“ngOnDestroy”生命周期钩子中取消订阅以避免内存泄漏。
这是一种可行的方法,可确保在Angular 14中使用NGRX存储时无泄漏的使用。