Home > Software design >  Can't create an object of type interface with data collected from ngrx store
Can't create an object of type interface with data collected from ngrx store

Time:05-21

I have this interface:

export interface AuthStateInterface {
    isSubmitting: boolean,
    X_HI_CODE: string,
    token: string,
    userId : number,
    roleId: number   
}

And I want to create an object of this interface type with some data collected from the ngrx store within another class with the method initializeValues() that creates the objects as bellow:

  initializeValues(): void {
    const data: AuthStateInterface = {
      isSubmitting: false,
      X_HI_CODE: this.store.pipe(select(xhicodeSelector)),
      token: this.store.pipe(select(tokenSelector)),
      userId : this.store.pipe(select(userIdSelector)),
      roleId: this.store.pipe(select( roleIdSelector)),
    };
    console.log('data', data)
  }

But Visual Studio errors out as you can see on the screenshot bellow: enter image description here

When I hover on the red alert, this is what it says:

enter image description here

I will be greatfull if anyone can help me fix this.

CodePudding user response:

There were several concepts of angular or typescript in general that I was misunderstanding. As @MikeOne said in the comments, Ngrx selectors return Observables, and I had to subscribe and assign them to the variables I've declared previously. So this is what I did:

1- I initialized the variables, not observables:

isSubmitting!: boolean
  token!: string
  roleId!: [number]
  userId!: string

2- I selected the data from the ngrx-store with the selector hook

ngOnInit(): void {
    this.initializeValues()
    this.getAllStaff()
  }
  
  initializeValues(): void {

    this.store
    .pipe(select(isSubmittingSelector), map((isSubmitting) => isSubmitting))
    .subscribe(value => this.isSubmitting = value);
    this.store

    .pipe(select(tokenSelector), map((token) => token))
    .subscribe(value => this.token = value);

    this.store
    .pipe(select(roleIdSelector), map((roleId) => roleId))
    .subscribe(value => this.roleId = value);

    this.store
    .pipe(select(userIdSelector), map((userId) => userId))
    .subscribe(value => this.userId = value);
  }

3- Then I used the values to create the data passed to next promise

   getAllPersnlValues() {
    const data: AuthStateInterface = {
      isSubmitting: this.isSubmitting,
      X_HI_CODE: this.HI_CODE,
      token: this.token,
      userId : this.userId,
      roleIds: this.roleId,
    };
    console.log('data', data);
   
    return this.persnlService.getPersnl(data)
    .pipe(
      map((response) => response)
    );
  }

There should be a shorter way to do it, and with my Reactjs background I had much more to learn about rxjs before boasting on simpler technics. But this approach made this task completed.

  • Related