繁体   English   中英

使用Firebase执行角度2应用程序的性能

[英]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文档 (位于页面底部)有一个非常方便的工具,可以帮助您为正确的行为选择合适的操作符。

我不关心流,我希望它工作,快速n'脏:

如果您不想过多地更改代码,可以使用Resolve防护,它将在加载组件之前获取数据。 看看文档

总之,您希望延迟渲染路由组件,直到获取所有必需的数据。 你需要一个解析器。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM