在 AngularFire 5 中返回 $key

Returning $key in AngularFire 5

我有以下适用于 AngularFire 5 的代码:

export class NavigationComponent {
    items: Observable<any[]>;
    constructor(db: AngularFireDatabase) {
        this.items = db.list('/pages', ref => {
            let query = ref.limitToLast(100).orderByChild('sortOrder');
            return query;
        }).valueChanges();
    }
}

但现在需要 return item.$key 显然在 AngularFire 5 中默认不再 returned。我看到迁移指南中提到需要 "map" 这个,但似乎无法在上面的代码上使用正确的语法。


更新: 遵循了下面的建议,它似乎奏效了,但新旧之间的行为似乎仍然存在一些差异。

<nav class="nav-standard">
    <app-logo></app-logo>
    <div class="nav-dropdown">
        <ul *ngFor="let item of items | async | filter : 'parent' : '00000000-0000-0000-0000-000000000000'" class="nav-dropdown">
            <li>
                <a mat-button class="mat-button" href="{{item.path}}" data-id="{{item.key}}" target="{{item.target}}" title="{{item.tooltip}}"  [attr.data-sort]="item.sortOrder" *ngIf="item.content; else elseBlock">{{item.menuText}}</a>
                <ng-template #elseBlock>
                    <a mat-button class="mat-button" data-id="{{item.key}}" target="{{item.target}}" title="{{item.tooltip}}">{{item.menuText}}</a>
                </ng-template>
                <ul class="nav-dropdown-content">
                    <li *ngFor="let childItem of items | async | filter : 'parent' : item.key" class="">
                        <a class="mat-button" href="{{childItem.path}}" data-id="{{childItem.key}}" target="{{childItem.target}}" title="{{childItem.tooltip}}" [attr.data-sort]="childItem.sortOrder">{{childItem.menuText}}</a>
                    </li>
                </ul>
            </li>
        </ul>   
    </div>
</nav>

嵌套的 *ngFor 似乎永远不会触发,而之前它确实触发过。嵌套的 *ngFor 中的 items 似乎是 null ??我发现如果我在我的组件中创建另一个名为 childItems 的 Observable 并为其分配重复的逻辑,它工作正常——但对我来说这感觉很脏和错误。我怎样才能让可观察对象中的数据持续足够长的时间以在嵌套的 *ngFor 中使用它?

在新的 AngularFire API 更改后,项目关键信息不再 'free'。你可以使用 '.snapshotChanges()':

而不是使用 '.valueChanges()' 将引用转换为 Observable
    .snapshotChanges()
    .map(changes => {
      return changes.map(change => ({key: change.payload.key, ...change.payload.val()}));
    })

从那时起,您可以使用 'item.key' 引用项目密钥(注意您不能使用 '$key')。