Home > front end >  Not able to get state changed value in other components angular with @ngrx/component-store
Not able to get state changed value in other components angular with @ngrx/component-store

Time:01-30

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 });
  }
}

I am trying to get changed value of state "storagetestId" in other component by calling store there but getting the intial value of "storagetestId" there how can I change state value and get changed value globally.I have shown my store file and component.ts below.

CodePudding user response:

Your issue is to move "providers: [ReservationStore]," from each component to a module.ts, like below

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

Here you can see an example https://stackblitz.com/edit/angular-ivy-bwvqpv?file=src/app/new-booking-modal/new-booking-modal.component.ts

  • Related