Angular中@ngrx/component-store跨组件获取状态变更值问题
解决@ngrx/component-store状态全局共享问题
你的问题核心是ReservationStore没有成为全局单例:在NewBookingModalPage的providers数组中声明了ReservationStore,这会导致每个使用该组件的地方都会创建独立的Store实例。其他组件注入的是全新的Store实例,自然看不到NewBookingModalPage里修改后的状态。
步骤1:将Store配置为全局单例
修改ReservationStore的@Injectable装饰器,添加providedIn: 'root',让Angular在根注入器中提供该Store,确保整个应用只有一个实例:
import { IStorageRoom } from '../models/storageRoom/storageRoom'; import { Injectable } from '@angular/core'; import { ComponentStore } from '@ngrx/component-store'; import { Observable } from 'rxjs'; export interface AddReservationState { StorageRooms: IStorageRoom[]; storagetestId: any; } @Injectable({ providedIn: 'root' }) // 配置为全局单例 export class ReservationStore extends ComponentStore<AddReservationState> { constructor() { super({ StorageRooms: [], storagetestId: 'initial value', }); } StorageRooms$: Observable<IStorageRoom[]> = this.select( (state) => state.StorageRooms ); storagetestId$: Observable<any> = this.select((state) => state.storagetestId); }
步骤2:移除组件内的Store声明
删掉NewBookingModalPage组件@Component装饰器中的providers: [ReservationStore],因为Store已经是全局单例,组件注入的就是同一个实例:
import { ReservationStore } from 'src/app/Store/AddReservation.store'; @Component({ selector: "app-new-booking-modal", templateUrl: "./new-booking-modal.page.html", styleUrls: ["./new-booking-modal.page.scss"], // 移除此行:providers: [ReservationStore], }) export class NewBookingModalPage implements OnInit { storagetestId$ = this.reservationStore.storagetestId$; constructor(private reservationStore: ReservationStore) {} ngOnInit() { this.bookingFun(' changed value'); } bookingFun(storagetestId) { this.reservationStore.patchState({ storagetestId }); } }
步骤3:其他组件直接注入使用
在需要获取状态的其他组件中,直接通过构造函数注入ReservationStore即可,无需额外配置:
import { ReservationStore } from 'src/app/Store/AddReservation.store'; @Component({ selector: "app-other-component", templateUrl: "./other-component.page.html", }) export class OtherComponent implements OnInit { storagetestId$ = this.reservationStore.storagetestId$; constructor(private reservationStore: ReservationStore) {} }
可选:用Updater封装状态修改(规范写法)
为了符合ComponentStore的设计规范,建议在Store内部定义专门的updater方法,替代组件直接调用patchState:
@Injectable({ providedIn: 'root' }) export class ReservationStore extends ComponentStore<AddReservationState> { // ... 现有代码 // 定义状态更新方法 readonly updateStorageTestId = this.updater((state, storagetestId: any) => ({ ...state, storagetestId })); }
组件中调用该方法:
bookingFun(storagetestId) { this.reservationStore.updateStorageTestId(storagetestId); }
内容的提问来源于stack exchange,提问作者Sahil Verma
相关产品推荐
相关产品推荐

