首页 > 解决方案 > Why I can't add any field in a firestore database with angular?

问题描述

I have my component that looks like this:

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';

import { AngularFirestore } from 'angularfire2/firestore';

@Component({
  selector: 'app-mission',
  templateUrl: './mission.component.html',
  styleUrls: ['./mission.component.css']
})
export class MissionComponent {

  public items: Observable<any[]>;

    constructor(db: AngularFirestore) {
        this.items = db.collection('/todos').valueChanges();
    }
    logForm(value: any) {
      console.log(value);

      this.db.collection("/todos").add({
          name: "Los Angeles",
          state: "CA",
          country: "USA"
      });

    }
}

but I don't understand why I have problems whit this.db and every time I get this error: Property 'db' does not exist on type 'MissionComponent'

Probably I'm missing something here..

标签: angularfirebasegoogle-cloud-firestore

解决方案


db 仅在构造函数范围内有效。

export class MissionComponent {

  public items: Observable<any[]>;
  private db: AngularFirestore; // this will be this.db

    constructor(db: AngularFirestore) {
        this.items = db.collection('/todos').valueChanges();
        this.db = db; // now you can use this.db
    }

推荐阅读