redux 无法使用@ngrx/component-store获取其他组件Angular 中的状态更改值

y53ybaqx  于 2023-01-30  发布在  其他
关注(0)|答案(1)|浏览(93)
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()
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);
}
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 });
  }
}

我试图通过调用store在其他组件中获取状态"storagetestId"的更改值,但在那里获取"storagetestId"的初始值。我如何全局更改状态值并获取更改值。我在下面显示了我的存储文件和组件. ts。

0lvr5msh

0lvr5msh1#

您的问题是将“提供者:[ReservationStore]”,从每个组件到一个模块.ts,如下所示

@NgModule({
  imports: [BrowserModule, FormsModule],
  declarations: [
    AppComponent,
    HelloComponent,
    NewBookingModalComponent,
    SecondViewComponent,
  ],
  bootstrap: [AppComponent],
  providers: [ReservationStore],
})
export class AppModule {}

这里您可以看到https://stackblitz.com/edit/angular-ivy-bwvqpv?file=src/app/new-booking-modal/new-booking-modal.component.ts示例

相关问题