Firestore: Add Custom Object to db

前端 未结 8 2028
庸人自扰
庸人自扰 2020-12-15 05:31

Good Morning,

I tried adding a new created object from this class:

export class Sponsor implements ISponsor {

  title: string;    
  description?: s         


        
8条回答
  •  南笙
    南笙 (楼主)
    2020-12-15 05:54

    If you use Angular and AngularFire2, you can use AngularFirestype. This module is meant to replace AngularFirestore and allow to get and set data to Firestore directly with custom objects.

    To do so, 3 steps are required:

    1. Install angular-firestype

    `npm install angular-firestype --save`
    

    2. Initialize AngularFirestype module with a mapping object

    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} = {
      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. Inject AngularFirestype service

    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;
       const user: User;
    
       constructor(db: AngularFirestype) {
           const usersCollection: Collection = db.collection('users');
           usersCollection.valueChanges().subscribe(users => this.users = users);
    
           const userDoc: Document = usersCollection.doc('user1');
           userDoc.valueChanges().subscribe(user => this.user = user);
           userDoc.set(this.user);
       }
    }
    

    You can basically use AngularFirestype like you use Angularfirestore.
    For more details, see the homepage here: https://github.com/bricepepin/angular-firestype.

提交回复
热议问题