I'm calling data from an NGXS state which when I console.log()
shows is present in the shape of the interface used to describe it. There's an items
property which is an array of 3 objects which I want to iterate over in my template. However when I target the items
property I get an error in vsCode telling me the property doesn't exist on that type and nothing renders on the screen.
My state model looks like this
export interface CattegoryIndexItem{
cattegory: string;
products: ProductIndexListItem[];
}
export interface ProductIndexListModel{ items: CattegoryIndexItem[]; }
my component looks like this
export class ProductPageComponent implements OnInit {
@Select() productIndexState$: Observable<ProductIndexListModel>;
constructor(private store: Store) {}
ngOnInit(): void {
this.store.dispatch(new GetProductIndexList());
}
showData(){
this.productIndexState$.subscribe(res => console.log(res));
}
}
inside my template
<article *ngFor="let item of productIndexState$.items | async">
<p>{{item.cattegory}}</p>
</article>
<button (click)="showData()">click</button>
When the page loads I get this error
error TS2339: Property 'items' does not exist on type 'Observable'.
I've never had this problem working with observables, is there something NGXS does that makes us need to access it differently?
Looks like a glitch in the template syntax - can't call .items
on the Observable itself, you want to call it on the object emitted by that Observable
.
So you need to pipe the Observable
via async
first e.g.
<ng-container *ngIf="productIndexState$ | async as productIndexState">
<article *ngFor="let item of productIndexState.items">
<p>{{item.cattegory}}</p>
</article>
<button (click)="showData()">click</button>
</ng-container>