【问题标题】:Ionic 2 angularfire2 Auth离子 2 angularfire2 身份验证
【发布时间】:2017-04-12 23:16:51
【问题描述】:

我在订阅 angularfire 身份验证时遇到问题。基本上发生的事情是当我这样订阅时:this.af.auth.first().subscribe(auth => { console.log(auth) }) auth 被打印到控制台两次而不是一次。我想我找到了这个问题的原因,但我不明白它为什么会发生或该怎么做。在我的 app.component.ts 中,我也像这样订阅 auth:

this.af.auth.first().subscribe(auth => {
  console.log("app")
  if (auth) {
    console.log('logged in');
    this.rootPage = "page1"
  } else {
    console.log('not logged in');
    this.rootPage = "login"
  }

})

如果我删除此订阅,那么我只有一张来自上述订阅的打印到控制台。我希望能够在这两个位置订阅,所以当应用程序加载时,如果需要,我可以重定向到登录,并且还能够从其他订阅中获取应用程序中的用户 uid。如果您有任何想法会很棒,谢谢!

【问题讨论】:

  • 你在哪里调用这个方法?在constructor 里面还是?
  • 在 app.Component.ts 中,它在 ngOnInit() 中被调用。另一个订阅是从页面中的 ionViewDidLoad() 调用的。如果我是精确的,它是提供程序中的一个函数进行订阅,那么该提供程序函数在页面的 ionViewDidLoad 中被调用

标签: angular firebase ionic2 observable angularfire2


【解决方案1】:

您必须在constructor 中调用它,如下所示。然后还要在unsubscribe 之后。

app.component.ts

constructor(platform: Platform, af: AngularFire) {
    const authListener = af.auth.subscribe(auth => {
       if (auth) {
        console.log('logged in');
        this.rootPage = "page1";
        authListener.unsubscribe();//unsubscribe here
      } else {
        console.log('not logged in');
        this.rootPage = "login";
        authListener.unsubscribe();//unsubscribe here
      }
    });

    platform.ready().then(() => {

    });
  }

【讨论】:

  • 如果您刷新页面意味着它会再次创建页面并再次打印控制台。您只能在浏览器上执行此操作。在真实设备上,您无法执行此操作。因此没问题。
【解决方案2】:

所以我尝试了,但它对我不起作用。这是我在 app.component.ts 中所做的

constructor(public af: AngularFire) {
    const authListener = af.auth.subscribe(user => {
      if (user) {
        console.log('logged in');
        this.rootPage = "page-conversations"
        authListener.unsubscribe();//unsubscribe here
      } else {
        console.log('not logged in');
        this.rootPage = "page-login"
        authListener.unsubscribe();//unsubscribe here
      }
    });
    this.initializeApp();
  }

那么这就是我在页面中所做的事情

ionViewDidLoad() {
    this.af.auth.subscribe(auth => {
         console.log("auth hello")
    })
  }

还有两个控制台日志。

更新 所以我发现了问题所在。我相信这是因为深层链接。当我加载页面时,我被确定为已登录,因此我被重定向到另一个页面。这会将 url 更改为:http://localhost:8100/#/page-conversations 然后当我刷新页面时,url 是相同的,因此该页面已加载但我的 app.component.ts 也确定我已登录,因此我被重定向到我已经登录的页面在。这就是为什么会有重复的调用。有没有人对如何解决这个问题有任何想法,这样它就不会发生?

【讨论】:

  • 所以我注意到当我第一次加载页面时只有一个控制台日志,但如果我刷新有两个。这可能是因为订阅清理不当造成的吗?问题一直存在,直到我停止页面并重做离子服务。
猜你喜欢
  • 2017-08-03
  • 1970-01-01
  • 2021-11-22
  • 2016-06-08
  • 1970-01-01
  • 1970-01-01
  • 2018-10-25
  • 2016-07-28
  • 1970-01-01
相关资源
最近更新 更多