如果你使用 Angular 和 AngularFire2,你可以使用 AngularFirestype。该模块旨在替换 AngularFirestore 并允许使用自定义对象直接获取和设置数据到 Firestore。
为此,需要 3 个步骤:
1.安装angular-firestype
`npm install angular-firestype --save`
2. 使用映射对象初始化 AngularFirestype 模块
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AngularFireModule } from 'angularfire2';
import { AngularFireAuthModule } from 'angularfire2/auth';
import { AngularFirestypeModule, ModelType } from 'angular-firestype';
import { environment } from '../environments/environment';
import { User } from './user.ts';
import { Address } from './address.ts';
import { Message } from './message.ts';
/**
* Definition of the app model mapping.
* For more information, see https://github.com/bricepepin/angular-firestype#mapping-object.
*/
const model: {[key: string]: ModelType<any>} = {
users: {
type: User,
arguments: ['username', 'image'],
structure: {
adress: Address
},
subcollections: {
messages: Message
}
}
};
@NgModule({
imports: [
AngularFireModule.initializeApp(environment.firebase),
AngularFireAuthModule,
AngularFirestypeModule.forRoot(model), // Import module using forRoot() to add mapping information
],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule {}
3.注入AngularFirestype服务
import { Component } from '@angular/core';
import { AngularFirestype, Collection, Document } from 'angular-firestype';
import { User } from './user.ts';
@Component({
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.css']
})
export class AppComponent {
const users: Observable<User[]>;
const user: User;
constructor(db: AngularFirestype) {
const usersCollection: Collection<User> = db.collection<User>('users');
usersCollection.valueChanges().subscribe(users => this.users = users);
const userDoc: Document<User> = usersCollection.doc('user1');
userDoc.valueChanges().subscribe(user => this.user = user);
userDoc.set(this.user);
}
}
您基本上可以像使用 Angularfirestore 一样使用 AngularFirestype。
有关更多详细信息,请参阅此处的主页:https ://github.com/bricepepin/angular-firestype 。