我正在使用ngxs状态管理。我需要退订选择器,还是由ngxs处理?
@Select(list)list$!: Observable<any>;
this.list$.subscribe((data) => console.log(data));
Run Code Online (Sandbox Code Playgroud)
对于第一个示例,可以与Async管道结合使用。异步管道将为您退订:
在您的ts文件中:
@Select(list) list: Observable<any>;
Run Code Online (Sandbox Code Playgroud)
在您的html文件中:
<ng-container *ngFor="let item of list | async">
</ng-container>
<!-- this will unsub automatically -->
Run Code Online (Sandbox Code Playgroud)
但是,当您想使用实际的订阅方法时,将需要手动取消订阅。最好的方法是使用takeUntil:
import {Subject} from 'rxjs';
import {takeUntil} from 'rxjs/operators';
@Component({
selector: 'app-some-component',
templateUrl: './toolbar.component.html',
styleUrls: ['./toolbar.component.scss']
})
export class SomeComponent implements OnInit, OnDestroy {
private destroy: Subject<boolean> = new Subject<boolean>();
constructor(private store: Store) {}
public ngOnInit(): void {
this.store.select(SomeState).pipe(takeUntil(this.destroy)).subscribe(value => {
this.someValue = value;
});
}
public ngOnDestroy(): void {
this.destroy.next(true);
this.destroy.unsubscribe();
}
}
Run Code Online (Sandbox Code Playgroud)
您可以将其pipe(takeUntil(this.destroy))用于组件中的每个订阅,而无需手动unsubscribe()为其添加每个订阅。
| 归档时间: |
|
| 查看次数: |
300 次 |
| 最近记录: |