【问题标题】:Performance of an angular 2 application with Firebase使用 Firebase 的 Angular 2 应用程序的性能
【发布时间】:2017-03-15 15:47:59
【问题描述】:

我一直在使用 angular2 和 firebase (angularfire2) 创建一个 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() 之外时,我得到一个错误 group is undefined ,我现在因为 angular 是异步的。我不知道我该怎么做?如何优化我的代码?,如何将函数AlreadyPaticipe(this.group.id,this.userConnected.uid) 放在getGroupById(this.idgroup).subscribe() 之外

提前致谢。

【问题讨论】:

  • 你不能,AlreadyPaticipe的目的是什么?
  • 或者你可以使用解析
  • AlreadyPaticipe 是一个检查用户是否是组成员的功能。

标签: javascript angular firebase angularfire


【解决方案1】:

一切都是流:

首先,你不应该订阅那么多,最好的做法是将你的 observable 组合成一个并只订阅一次,因为每次订阅时,你都需要在组件被销毁时进行清理(不适用于 http,不过,ActivatedRoute 都不是),您最终会强制管理您的订阅(这不是 RXjs 的目标)。你可以找到a good article on this topic here

您必须将所有内容都视为流,您的所有属性都是可观察的:

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>

或者如果你不想使用管道,你可以将所有这些 observable 组合起来,并且只订阅一次:

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() in ngOnDestroy()

rxJS docs(页面底部)上有一个非常方便的工具,可帮助您为正确的行为选择正确的运算符。

我不关心流,我希望它能够工作,快速而不是肮脏:

如果您不想过多地更改代码,则可以使用 Resolve 守卫,它会在加载组件之前获取数据。 Take a look at the docs:

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

【讨论】:

    猜你喜欢
    • 2018-01-16
    • 1970-01-01
    • 2021-09-16
    • 1970-01-01
    • 2015-11-01
    • 1970-01-01
    • 2018-07-18
    • 1970-01-01
    • 2020-06-11
    相关资源
    最近更新 更多