Home > Software design >  How to access nested property from ngrx selector Observable?
How to access nested property from ngrx selector Observable?

Time:12-22

Initial Data definition and Interface:

export interface IInitialData {
    version: {
        patch?: string;
        Version: string,
        build: number,
    };
}

export const initialStateInitialData = {
    version: {
        build: 0,
        Version: '1',
    },
};

I have the following selectors in the selectors file:

export const selectInitialDataFeature = createFeatureSelector<IInitialData>('initialData');`

export const selectInitialData = createSelector(
    selectInitialDataFeature,
    initialData => {
        return initialData;
    },
);

export const selectInitialDataVersion = createSelector(
    selectInitialData,
    initialData => {
        return initialData.version.Version;
    },
);

Accessing 2nd one from component file:

public version$ = this.store.select(selectInitialDataVersion);

And from template file:

[value]="version$ | async"

This works fine.

However, following returns error "Unresolved variable version"

public initialData$ = this.store.select(selectInitialData);
[value]="initialData$.version.Version | async"`

How do I access the variable version.Version in this manner?

CodePudding user response:

<ng-container *ngIf="(initialData$ | async) as myInitialData">
  <my-component [value]="myInitialData.version.Version">
  </my-component>
</ng-container>

You are trying to access the value of your Observable without subscribing it, which in this case, before using the async pipe

CodePudding user response:

You need to use the async pipe directly after the observable, then then access the properties:

[value]="(initialData$ | async).version.Version"
  • Related