2017-02-13 97 views
0

我正在构建带有Ionic 2和Firebase的基本移动应用程序。我正在使用AngularFire2从我的应用程序访问Firebase。将FirebaseListObservable存储在自定义类中

我在某个特定点上挣扎。

我想坚持我当前的用户。所以,我创建了一个用户等级:

import { FirebaseListObservable } from 'angularfire2'; 
import { DatabaseService } from '../providers/database.service'; 

export class User { 

    uid: string; 
    observableList: FirebaseListObservable<any>; 

    constructor(uid: string, user: FirebaseListObservable<any>) { 
    this.uid = uid; 
    this.observableList = user; 
    } 

} 

一个UserService,让我来完成与用户相关的所有操作:

import { Injectable } from '@angular/core'; 

import { FirebaseListObservable } from 'angularfire2'; 

import { DatabaseService } from './database.service'; 
import { User } from '../app/user'; 

@Injectable() 
export class UserService { 

    constructor(private _db: DatabaseService) {} 

    getUserAsObservableList(uid: string): FirebaseListObservable<any> { 
    return this._db.getUserAsObservableList(uid); 
    } 
} 

的DatabaseService getUserAsObservableList设计如下:

getUserAsObservableList(uid: string): FirebaseListObservable<any> { 
    let ref = '/' + this.base + '/users/' + uid; 
    return this.af.database.list(ref); 
    } 

的我在Firebase中访问的数据: enter image description here

在我的部分我做到以下几点:

constructor(public navCtrl: NavController, private _auth: AuthService, private _db: DatabaseService, private _user: UserService) { 
     console.log('HomePage constructor called.'); 
     this.user = new User(this._auth.uid, this._user.getUserAsObservableList(this._auth.uid)); 
     console.log('User: ', this.user); 
     } 

最后,在我的HTML查看下面的代码:

<h2>Welcome to Ionic!</h2> 

    <ul> 
    <li *ngFor="let item of user.observableList | async"> 
     {{ item | json }} 
    </li> 
    </ul> 

提供了以下的输出: enter image description here

于是我试着访问公共节点:

<ul> 
    <li *ngFor="let item of user.observableList | async"> 
     {{ item.public | json }} 
    </li> 
    </ul> 

并得到以下内容: enter image description here

我在做什么错在我的代码?更多全球范围内,我在这里使用错误的模式?我应该以不同的方式实施这个吗?

感谢

回答

0

的问题是,既然你是检索用户的列表的属性,则无法通过使用密钥访问它们。你有两种选择来实现你想要的。您可以检索您的用户作为对象,或者您需要环绕要显示像这样的数据*ngIf

<span *ngIf="item.$key == 'public'"> 
    {{item | json}} 
</span> 
+0

我试过* ngIf包装和它的工作,谢谢!至于您的第一个建议,要将用户作为对象进行检索,您的意思是使用FirebaseObjectObservable吗? –

+1

是的,这就是我的意思 –

相关问题