angularjs 如何在Map时将www.example.com包含doc.id在doc.data()中?

hl0ma9xz  于 2022-10-31  发布在  Angular
关注(0)|答案(2)|浏览(215)

我想将我的数据绑定到下面的HTML表:

<table id="tableAccounts">
        <thead>
            <tr>
                <th>No.</th>
                <th>Status</th>
                <th>Code</th>
                <th>Name</th>
                <th>Deposit / Credit Limit</th>
                <th>Date Joined</th>
                <th>Total Course</th>
                <th>UPV Cost</th>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="account in accounts">
                <td>{{ $index + 1 }}</td>
                <td>{{ account.AccStatus }}</td>
                <td>{{ account.id }}</td>
                <td>{{ account.AccName }}</td>
                <td>{{ account.Deposit }}</td>
                <td>{{ account.DateJoined }}</td>
                <td>{{ account.TotalCourse }}</td>
                <td>{{ account.UpvCost }}</td>
            </tr>
        </tbody>
    </table>

下面的代码在我的AngularJS控制器中:

var db = firebase.firestore();

        db.collection("Accounts").get().then((querySnapshot) => {
            if (!querySnapshot.empty) {
                $scope.accounts = querySnapshot.docs.map(doc => doc.data());
                $scope.$apply();
            }
        });

但是上面的代码在执行Map时没有在doc.data()中包含doc.id。我如何在这个场景中包含doc.id,以便它可以绑定到我的HTML表的Code列?

dgenwo3n

dgenwo3n1#

使用spread操作符应该可以实现,它的行为类似于Object.assign(),只是它不触发setter,也不改变任何对象:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

querySnapshot.docs.map(doc => ({...doc.data(), id:doc.id}))
gopyfrb3

gopyfrb32#

要获得doc.id,必须在代码中使用snapshotChanges(),如下所示:

db.collection("Accounts").snapshotChanges().map(actions => {
  return actions.map(a => {
    const data = a.payload.doc.data();
    const id = a.payload.doc.id;
    return { id, ...data };
  });
});

相关问题