我使用 NGXS 进行状态管理,并使用 firestore-plugin( https://github.com/ngxs-labs/firestore-plugin )。
如何在我的对象中添加文档的 id?
我已经创建了我的商店:
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';
}
我已经创建了我的状态和操作:
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 });
}
}
我的模型看起来像这样:
interface Spot {
id: string;
name: string;
description: string;
checkinValue: number;
imageUrl: string;
coordinates: firebase.firestore.GeoPoint;
}
很明显,id 不在我的 firebase 文档中,而是在识别它。但是拥有它肯定对我有用。
我想我应该覆盖 NgxsFirestore 中的某些内容,但我不知道怎么做?是否必须将其包含在文档中?
你可以!您只需要在您的服务中创建一个属性,idField
如下所示:
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';
idField = 'spotId'
}
在这种情况下,它将在属性下添加 DocumentId spotId
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句