我目前正在尝试使用googles firebase构建一些东西,我遇到了一个问题。看来这段代码
export class FirebaseService {
items: Observable<Item[]>;
constructor(private db: AngularFireDatabase){
}
getBusinesses(){
this.businesses = this.db.list('/items').valueChanges() as Observable<Item[]>
return this.items;
}
}
用于为您提供一个带有$ key的对象作为数据库中对象的键(至少这是我在阅读的教程中所做的)
问题是,$ key是未定义的,我想知道,我如何获得list-method返回包含密钥的对象。一直在尝试一段时间,但我真的找不到错误。如果有人知道答案,我会很高兴。
[编辑]
https://github.com/angular/angularfire2/blob/master/docs/version-5-upgrade.md 这让我更接近解决方案。看来,angularfire2已经看到了5.0.0版本的一些重大变化。但是由于我还在学习,我无法将它真正集成到我的代码中。目前它看起来像这样
firebase.service.ts
import { Injectable } from '@angular/core';
import { AngularFireModule } from 'angularfire2';
import { AngularFireDatabase, AngularFireDatabaseModule } from 'angularfire2/database';
import { FirebaseListObservable } from 'angularfire2/database-deprecated';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import {Business} from '../Business';
import {Category} from '../Category';
@Injectable()
export class FirebaseService {
businesses : Observable<Business[]>;
categories : Observable<Category[]>;
constructor(private db: AngularFireDatabase){
}
getBusinesses(){
this.businesses = this.db.object('/businesses').snapshotChanges().map(action => {
console.log('ACTION:');
console.log(action);
const $key = action.payload.key;
const data = {$key, ...action.payload.val()};
return data;
}) as Observable<Business[]>;
return this.businesses;
}
}
和app.component.ts
import { Component, OnInit } from '@angular/core';
import { AngularFireDatabase } from 'angularfire2/database';
import { Observable } from 'rxjs/Observable';
import { FirebaseService } from './services/firebase.service';
import { Business } from './Business';
import { Category } from './Category';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
items: Observable<any[]>;
businesses: Business[];
categories: Category[];
appState: string;
activeKey: string;
constructor(private _firebaseService: FirebaseService){
}
ngOnInit(){
this._firebaseService.getBusinesses().subscribe(businesses => {
console.log('Businesses:');
console.log(businesses);
this.businesses = businesses;
});
}
}
现在我的结果并不像我希望的那样。基本上我要回来的是
{
0: {
Key01: "xyz",
Key02: "yyy"
},
1: {
Key11: "zyx",
Key12: "zzz"
},
$key: "businesses"
}
我会继续努力。也许你知道我做错了什么。感谢您的帮助到目前为止
[/编辑]
答案 0 :(得分:0)
您需要将项目声明为FirebaseListObservable<Item[]>
并执行getBusinesses()调用,如下所示:
this.items= this.af.list('/items') as FirebaseListObservable<Item[]>;
希望这会帮助您获得$ key值。