简体   繁体   English

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

[英]Angular 6: error while passing data to FireBase Collection

Im using Firebase for simple CRUD operations. 我使用Firebase进行简单的CRUD操作。 But when trying to add a value to my collection, I get the following error: CollectionReference.add() requires its first argument to be of type object, but it was: undefined 但是,当尝试向集合中添加一个值时,出现以下错误: CollectionReference.add() requires its first argument to be of type object, but it was: undefined

The Model TS (same as the database) TS型(与数据库相同)

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

The Service 服务

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);
  }

Component TS 组件TS

export class MainComponent implements OnInit {

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

  ngOnInit() {
  }


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

}

And the HTML 和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>

Could someone explain me why do I get this error and how to solve it? 有人可以向我解释为什么我会收到此错误以及如何解决该错误?

EDIT: I pretent to add a new value to receipe, in this collection. 编辑:我在这个集合中假装为receipe添加一个新值。 The trhee documents above are empty 上面的trhee文件为空 在此处输入图片说明

instead of using 'valueChanges()' function in 'this.users = this.usersCollection.valueChanges();' 而不是在“ this.users = this.usersCollection.valueChanges();”中使用“ valueChanges()”函数

try using: 尝试使用:

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

.snapshotChanges will capture id and other metadata information of the collection. .snapshotChanges将捕获集合的ID和其他元数据信息。

The solution is on the View. 解决方案在视图上。 Data has to be passed on the HTML, as Peter suggested 正如彼得建议的,数据必须通过HTML传递

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM