[英]Performance of an angular 2 application with Firebase
我一直在使用帶有firebase(angularfire2)的angular2創建一個web應用程序,我想知道我的開發方法是否已經優化。
當用戶選擇一個組時,我會檢查他是否已經是該組的成員。
ngOnInit() {
this.af.auth.subscribe(auth => {
if(auth) {
this.userConnected = auth;
}
});
this.router.params.subscribe(params=>{
this.idgroup=params['idgroup'];
});
this._groupService.getGroupById(this.idgroup).subscribe(
(group)=>{
this.group=group;
this.AlreadyPaticipe(this.group.id,this.userConnected.uid),
}
);
}
這個方法是有效的,但是當我將函數AlreadyPaticipe(this.group.id,this.userConnected.uid)
放在getGroupById(this.idgroup).subscribe()
,我得到一個錯誤組是未定的,我現在因為angular是asynchrone。 我不知道我怎么能這樣做? 我如何優化我的代碼?,我如何將函數AlreadyPaticipe(this.group.id,this.userConnected.uid)
getGroupById(this.idgroup).subscribe()
提前致謝。
首先,您不應該訂閱那么多,最好的做法是將您的observable合並為一個並只訂閱一次,因為每次訂閱時,您需要在組件被銷毀時進行清理(不是http,不是ActivatedRoute雖然並且你最終必須管理你的訂閱(這不是RXjs的目標)。 你可以在這里找到關於這個主題的好文章 。
您必須將所有內容都視為流,所有屬性都是可觀察的:
this.user$ = this.af.auth.share(); //not sure of the share, I don't know firebase, don't know what it implies...
this.group$ = this.router.params.map(params => params["idgroup"])
.switchMap(groupID => this.groupService.getGroupById(groupID)).share();
// I imagine that AlreadyPaticipe return true or false, but maybe i'm wrong
this.isMemberOfGroup$ = Observable.combineLatest(
this.group$,
this.user$.filter(user => user !== null)
).flatMap(([group, user]) => this.AlreadyPaticipe(groupID, user.uid));
你甚至不必訂閱! 在模板中,您只需要使用async
管道。 例如:
<span>user: {{user$|async}}</span>
<span>group : {{group$|async}}</span>
<span>member of group : {{isMemberOfGroup$|async}}</span>
或者,如果您不想使用管道,您可以將所有可觀察的和僅訂閱組合一次:
this.subscription = Observable.combineLatest(
this.group$,
this.user$,
this.isMemberOfGroup$
).do(([group, user, memberofGroup]) => {
this.group = group;
this.user = user;
this.isMemberofGroup = memberofGroup;
}).subscribe()
在這種情況下,不要忘記this.subscription.unsubscribe()
中的ngOnDestroy()
rxJS文檔 (位於頁面底部)有一個非常方便的工具,可以幫助您為正確的行為選擇合適的操作符。
如果您不想過多地更改代碼,可以使用Resolve防護,它將在加載組件之前獲取數據。 看看文檔 :
總之,您希望延遲渲染路由組件,直到獲取所有必需的數據。 你需要一個解析器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.