文档不会从firestore中删除

时间:2018-03-08 05:41:35

标签: angular angularfire2

我正在使用angularfire 2.我想通过按下按钮从firestore中删除一个集合。当我按下一个按钮控制台显示我删除了一个文件,但该文件仍在那里。在firestore中我存储了一个集合(用户),我有很多文档,我想从集合中删除一个特定的文档。

app.component.ts

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

import { AngularFirestore, AngularFirestoreCollection } from 
'angularfire2/firestore';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';

@Component({
templateUrl: 'app.component.html'
}) 
export class AppComponent implements OnInit  {
users: Observable<any[]>;


constructor(private afs: AngularFirestore) {


this.users = this.afs.collection('users').valueChanges();
}

ngOnInit() {
 this.usersCol = this.afs.collection('users');

 this.users = this.usersCol.snapshotChanges()
  .map(actions => {
    return actions.map(a => {
      const data = a.payload.doc.data() as User;
      const id = a.payload.doc.id;
      return { id, data };
    })
  })

}

 onDelete(userId)
  {
  this.afs.doc('users/'+userId).delete();


  }

  }

app.component.html

<div class="card-body">
      <table class="table">
        <thead>
          <tr>


            <th>Photo</th>
           <th>Name</th>
           <th>Email</th>
           <th>Rating</th>

              <th >delete</th>

          </tr>
        </thead>
        <tbody>
          <tr *ngFor="let user of users | async">

            <td >
              {{user.photoUrl}}
            </td>
    <td>
                     {{user.userName}}

                   </td>
                   <td >
                     {{user.email}}
                   </td>
                   <td>

                   {{user.rating}}
                 </td>

                   <td>

                   {{user.id}}
                 </td>


                   <td>
                       <button class="btn btn-sm btn-danger"  
      (click)="onDelete(user.id)">delete</button>
                   </td>


  </tr>
        </tbody>
      </table>
   </div>

任何帮助将不胜感激。三江源

1 个答案:

答案 0 :(得分:0)

1-您正在使用两个不同的值初始化您的用户。在代码中删除此行:

this.users = this.afs.collection('users').valueChanges();

2- ngOnInit中返回的对象是一个像这样的数组{1:id,2:user}。

您应该返回一个User对象:

this.users = this.usersCol.snapshotChanges()
  .map(actions => {
    return actions.map(a => {
      let data = a.payload.doc.data() as User;
      data.id = a.payload.doc.id;
      return data;
    })
  })

通过输入代码,您可以避免此类错误:

...
users: Observable<User[]>;
...
this.afs.collection<User>('users');
...