【问题标题】:retrieve a document by id from collection of firestore on angular从 Angular 上的 firestore 集合中按 id 检索文档
【发布时间】:2018-04-01 18:55:23
【问题描述】:

我有一个包含多个文档的活动集合。我想在单击按钮上检索特定文档。

收藏:活动

文档 ID:自动 ID

字段:activityid、locked、section、maxPlayers、name

我在这里检索整个集合

this.activities = afs.collection('activities', x => x.orderBy('section', 
'asc')).valueChanges();

我将这些集合显示为;

<tr *ngFor="let activity of activities | async  | paginate: { itemsPerPage: 10, currentPage: p }; let i =index">
    <td>
        {{activity.section}}
    </td>
    <td >
        {{activity.name}}
    </td>
    <td>
        {{activity.maxPlayers}}
    </td>
    <td>
        {{activity.locked}}
    </td>
    <td>
        <button type="button" class="btn btn-success" 
            (click)="onEdit(activity.id);  secondModal.show() "><i 
            class="fa fa-pencil"></i>
                       Edit
        </button>
</td>

我在 OnEdit() 函数上传递了一个 id 参数。在 OnEdit 函数中,我想按 id 检索选择性文档。并将模型中的文档字段显示为:

<div *ngFor="let activity of activities | async >
    {{activity.section}}        
    {{activity.name}}                    
    {{activity.maxPlayers}}                    
    {{activity.locked}}

我尝试了很多想法,但没有奏效。它始终显示所有文件。我只想检索通过按钮单击的文档。

【问题讨论】:

  • 代码中 onEdit 和 secondModal.show() 函数的内容是什么?
  • 在 onEdit() 函数中:this.afs.doc("activities/"+actId).valueChanges();其中 actId 是我在 onClick 方法中传递的文档的 ID。而 secondModal.show() 正在调用一个模式来显示这些文档字段。但是我的模态显示了一个集合的所有文档。
  • 查看我的回答,希望对您有所帮助。

标签: angular google-cloud-firestore angularfire2


【解决方案1】:

编辑: 在您的activities.component.html 文件中:

  <td>
    <button type="button" class="btn btn-success" 
      (click)="onEdit(activity);  secondModal.show()"><i 
      class="fa fa-pencil"></i>
        Edit
     </button>
  </td>

activities.component.ts 文件中:

onEdit(activity){ 
  this.afs.doc("activities/"+activity.id).valueChanges();
  this.activity = activity;
  ..... your code
}

你必须在你的activities.component.ts 文件中声明一个activity 变量,就像你对activities 变量所做的那样,你可以在你的模态模板中使用它而不是活动而不需要*ngFor 指令。

【讨论】:

  • 如何在不使用 *ngFor 的情况下获取字段?它无法识别我的字段,它向我显示一个错误。在第一个中,我如何获取文件?对不起,我对角度很陌生,请您更详细地说明您的解决方案。感谢您的帮助。
  • 我有activities.component.html 文件,其中的表格显示了集合中的所有活动。该文件中还有模型模板,我想在其中检索用户想要查看的选择性文档。
  • 我为你更新了我的答案,也许你必须在 "this.activity = activity;" 之后的 "onEdit" 函数中放置 "secondModal.show()" 函数.
  • 已完成此操作,但出现错误 secondModal 无法检索字段。在模态中,我正在检索我的值,例如 {{activity.locked}}。
  • 可能我听不懂你,但现在我设法检索特定文档。在 onEdit 方法中我这样做:** this.actDoc = this.afs.doc('activities/'+actId); this.activity = this.actDoc.valueChanges();** 然后在模态中我将它们检索为 {{(activity | async)?.locked }} 感谢您的帮助,非常感谢:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-11
  • 2018-04-04
  • 1970-01-01
  • 2018-08-22
相关资源
最近更新 更多