I'm using NGXS for my state management and also using the firestore-plugin(https://github.com/ngxs-labs/firestore-plugin).
How do I add the id of the document inside my object?
I've created my store:
import { Injectable } from '@angular/core';
import { NgxsFirestore } from '@ngxs-labs/firestore-plugin';
@Injectable({
providedIn: 'root',
})
export class SpotsFirestore extends NgxsFirestore<Spot> {
protected path = 'seasons/2021/spots';
}
I've created my state&actions:
import { Injectable } from '@angular/core';
import { Emitted, NgxsFirestoreConnect, StreamEmitted } from '@ngxs-labs/firestore-plugin';
import { Action, NgxsOnInit, Selector, State, StateContext } from '@ngxs/store';
import { InitializeSpotsAction } from './spots.actions';
import { SpotsFirestore } from './spots.firestore';
export interface SpotsStateModel {
spots: Spot[];
}
@State<SpotsStateModel>({
name: 'spots',
defaults: {
spots: [],
},
})
@Injectable()
export class SpotsState implements NgxsOnInit {
@Selector()
static spots(state: SpotsStateModel) {
return state.spots;
}
constructor(private spotsFireStore: SpotsFirestore, private ngxsFirestoreConnect: NgxsFirestoreConnect) {}
ngxsOnInit(ctx?: StateContext<any>) {
this.ngxsFirestoreConnect.connect(InitializeSpotsAction, {
to: (action) => this.spotsFireStore.collection$(),
});
}
@Action(StreamEmitted(InitializeSpotsAction))
getAllEmitted(ctx: StateContext<SpotsStateModel>, { action, payload }: Emitted<InitializeSpotsAction, Spot[]>) {
ctx.patchState({ spots: payload });
}
}
and my model looks like this:
interface Spot {
id: string;
name: string;
description: string;
checkinValue: number;
imageUrl: string;
coordinates: firebase.firestore.GeoPoint;
}
so obviously, id isn't inside my firebase document but is identifying it. But it will definitely be usefull for me to have it.
I guess I should override something in NgxsFirestore, but I can't figure out what on how? Is it mandatory to have it inside the document?
You can! You just need create a property in your service called
idField
like shown bellow:In this case, it will add the DocumentId under the property
spotId
reference: https://github.com/ngxs-labs/firestore-plugin