在AngularFire 5中返回$ key [英] Returning $key in AngularFire 5
问题描述
我有以下适用于AngularFire 5的代码:
I have the following code that works with 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中不再默认返回.我在迁移指南中看到需要映射"此内容,但是似乎无法获得正确的语法上面的代码.
But now need to return item.$key
which apparently is no longer returned by default in AngularFire 5. I see mention in the migration guide of needing to "map" this, but can't seem to get the right syntax working on the above code.
更新:按照以下建议进行操作,它似乎奏效了,但新旧行为之间仍然存在一些差异.
Update: followed the advice below, and it seemed to have worked but there appears to be some difference still between the behavior between old and new.
<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中使用它?
The nested *ngFor never seems to fire, whereas before it did. It appears that items in the nested *ngFor is null
?? I found if I create another Observable in my component called childItems and assign duplicate logic to that, it works okay -- but to me that feels dirty and wrong. How can I get the data in the observable to persist long enough to use it in the nested *ngFor ?
推荐答案
项密钥信息不再免费".可以使用'.snapshotChanges()':
item key information isn't 'free' anymore upon the new AngularFire API changes. Instead of use '.valueChanges()' to turn reference into Observable, you can use '.snapshotChanges()':
.snapshotChanges()
.map(changes => {
return changes.map(change => ({key: change.payload.key, ...change.payload.val()}));
})
从那时起,您可以使用'item.key'来引用项目密钥(注意,您不能使用'$ key').
from then on you can reference item key by using 'item.key' (notice that you cannot use '$key').
这篇关于在AngularFire 5中返回$ key的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!