Angular 6:将数据传递到FireBase Collection时出错

时间:2018-10-28 22:58:38

标签: angular typescript firebase

我使用Firebase进行简单的CRUD操作。但是,当尝试向集合中添加值时,出现以下错误:CollectionReference.add() requires its first argument to be of type object, but it was: undefined

TS型(与数据库相同)

  export interface Users {
  id?: number,
  user?: string,
  recipe?: string
}

服务

export class UsersService {

  usersCollection: AngularFirestoreCollection<Users>;
  userDoc: AngularFirestoreDocument<Users>;
  users: Observable<Users[]>;
  user: Observable<Users>;

  constructor(private afs: AngularFirestore) {
    this.usersCollection = afs.collection<Users>('recipes');
    this.users = this.usersCollection.valueChanges();



}

   addRecipe(recipe: Users) {
     this.usersCollection.add(recipe);
  }

组件TS

export class MainComponent implements OnInit {

  users:Users;
  constructor(private usersService:UsersService) { }

  ngOnInit() {
  }


addRecipe(recipe:Users){
  this.usersService.addRecipe(recipe);
}

}

和HTML

<div class="container">

<div class="jumbotron">
  <div class="row">
    <div class="col-md-6 offset-md-3">
      <input class="form-control" type=text [(ngModel)]="users">
    </div>
    <button class="btn btn-danger" (click)="addRecipe()">Recipe</button>
  </div>
</div>

</div>

有人可以解释一下我为什么会出现此错误以及如何解决它吗?

编辑:在这个集合中,我冒充一个新值来添加。上面的trhee文档为空enter image description here

2 个答案:

答案 0 :(得分:0)

而不是在'this.users = this.usersCollection.valueChanges();'中使用'valueChanges()'函数

尝试使用:

    .snapshotChanges()
    .pipe(
     map(changes => {
      return changes.map(change => ({key: change.payload.key, ...change.payload.val()}));
     }))

.snapshotChanges将捕获集合的ID和其他元数据信息。

答案 1 :(得分:0)

解决方案在视图上。正如彼得建议的,数据必须通过HTML传递

      <input #inputName  type="text" class="form-control" >
 <button class="btn btn-danger" (click)="addRecipe({user: inputName.value})">Save</button>