我想知道使用Angular 2和AngularFire2处理类中动态属性的最佳实践是什么。
在我的Firebase数据库中,我有以下方案:
$company
- users
-- $user
--- public
--- chats
--- events
---- $event
----- id
----- timestamp
- events
-- $event
--- id
--- timestamp
--- joiners
---- $joiner
----- uid
我实施了一项用户服务:
// UserService
@Injectable()
export class UserService {
constructor(private af: AngularFire, private dbService: DatabaseService) {}
getUser(uid: string): Observable<User> {
console.log('Retrieveing user for uid ', uid);
let now: number = Date.now();
return Observable.combineLatest(
this.dbService.getNodeAsObjectObservable(true, `users/${uid}/public`),
this.dbService.getNodeAsListObservable(true, `users/${uid}/events`, {
query: {
orderByChild: 'timestamp',
startAt: now
}
})
).map(([info, joinedEvents]) => (new User({uid, info, joinedEvents})));
}
}
数据库服务:
@Injectable()
export class DatabaseService {
public root: any;
public queue: any;
public company: any;
constructor(private af: AngularFire) {
console.log('DatabaseService constructor');
}
setCompany(company: string): void {
this.company = company;
}
// Utilities
getNodeAsListObservable(companyRelated: boolean, node: string, query?: any): FirebaseListObservable<any> {
console.log('DatabaseService - getNodeAsListObservable: with args ',
companyRelated, node, query
);
let ref: string;
companyRelated ? ref = this.company : ref = this.root;
if (query) {
return this.af.database.list(`${ref}/${node}`, query);
} else {
return this.af.database.list(`${ref}/${node}`);
}
}
getNodeAsObjectObservable(companyRelated: boolean, node: string): FirebaseObjectObservable<any> {
let ref: any;
companyRelated ? ref = this.company : ref = this.root;
return this.af.database.object(`${ref}/${node}`);
}
}
在我的家里:
user: Observable<User>;
constructor(public navCtrl: NavController, private userService: UserService) {
console.log('HomePage constructor');
}
ngOnInit(): void {
// Retrieve current user
this.user = this.userService.getUser('abizhdiuh738937bj');
}
最后我的User类定义如下:
export interface IUser {
uid: string;
info: any;
//joinedEvents?:
}
export class User implements IUser {
uid: string;
info: any;
joinedEvents?: FirebaseListObservable<Event>;
constructor(obj?: any) {
if (obj.uid) this.uid = obj.uid;
if (obj.info) this.info = obj.info;
if (obj.joinedEvents) {
for (let i = 0; i < obj.joinedEvents.length; i++) {
// Q1: how to retrieve details of each event
}
}
}
}
对于每个joinEvents,我想在视图中显示它之前检索它的详细信息。
所以我的问题是什么是解决这个问题的最佳方式?
我有几个想法:
在getUser()(在UserService中)一次
this.dbService.getNodeAsListObservable(true,users/${uid}/events
,{
查询:{
orderByChild:&#39; timestamp&#39;,
startAt:现在
}
})
完成后调用getEvent(event_id)函数。怎么做到这一点?
我很失落如何处理这种封装的复杂性。此外,我将不得不处理与每个用户所属的聊天非常相似的内容...希望你能提供帮助。感谢