【问题标题】:Returning $key in AngularFire 5在 AngularFire 5 中返回 $key
【发布时间】:2018-05-05 18:46:17
【问题描述】:

我有以下适用于 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();
    }
}

但现在需要返回 item.$key,显然在 AngularFire 5 中默认不再返回。我在迁移指南中看到需要“映射”这个,但似乎无法获得正确的语法上面的代码。


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

<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 并为其分配重复的逻辑,它可以正常工作 - 但对我来说,这感觉很脏和错误。如何让 observable 中的数据持续足够长的时间以在嵌套的 *ngFor 中使用它?

【问题讨论】:

    标签: angularfire angularfire5


    【解决方案1】:

    在新的 AngularFire API 更改后,项目密钥信息不再“免费”。您可以使用 '.snapshotChanges()',而不是使用 '.valueChanges()' 将引用转换为 Observable:

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

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

    【讨论】:

    • 这似乎工作——有点——我的嵌套 ngFor 似乎永远不会触发:-(
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-12
    • 1970-01-01
    • 2015-06-24
    • 2015-07-05
    • 1970-01-01
    相关资源
    最近更新 更多