简体   繁体   English

firebase.auth()。当刷新页面时,currentUser返回null

[英]firebase.auth().currentUser returns null when page is refreshed

I added the function as you mentioned but when i login it shows this error: 我添加了您提到的功能,但是当我登录时显示此错误:

TypeError: Cannot set property 'photo' of undefined
    at feed.page.ts:32
    at auth.esm.js:326
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:391)
    at Object.onInvoke (core.js:17299)
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:390)
    at Zone.push../node_modules/zone.js/dist/zone.js.Zone.run (zone.js:150)
    at zone.js:889
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:423)
    at Object.onInvokeTask (core.js:17290)
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:422)
    at resolvePromise (zone.js:831)
    at zone.js:896
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:423)
    at Object.onInvokeTask (core.js:17290)
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:422)
    at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (zone.js:195)
    at drainMicroTaskQueue (zone.js:601)
    at push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask (zone.js:502)
    at ZoneTask.invoke (zone.js:487)
    at timer (zone.js:2281)

If I refresh the page it says : 如果我刷新页面,它说:

 getEvents() is not a function 

Changes i made and still getting the error. 我做的更改仍然得到错误。 It is wierd because when i login and redirect toe FeedPage i get error photo of undefined, if i refresh i get getEvents() is not e function.After i refresh the photo variable is null in the feed.html and cannot be binded to the ngModel and show the photo in avatar. 这是奇怪的,因为当我登录并重定向脚趾FeedPage我得到undefined的错误照片,如果我刷新我得到getEvents()不是e函数。我刷新后照片变量在feed.html中为null并且无法绑定到ngModel并在头像中显示照片。

events: any[] = [];
  likes: any[] = [];
  pageSize = 10;
  cursor: any; // can be declared as DocumentSnapshot
  infiniteEvent: any;
  state: any;
  private photo = '';

  // tslint:disable-next-line: max-line-length
  constructor(public navCtrl: NavController, private loadingCtrl: LoadingController, private toastCtrl: ToastController, private http: HttpClient, public actionSheetCtrl: ActionSheetController, public alertCtrl: AlertController, public modalCtrl: ModalController, public popoverCtrl: PopoverController) {

    firebase.auth().onAuthStateChanged(function (user) {
      if (user) {
        this.photo = user.photoURL;
        this.getEvents();
      } else {
        console.log('Not authenticated');
        // No user is signed in.
      }
    });
  }


  public async getEvents() {
    const loading = await this.loadingCtrl.create({
      message: 'Loading events...'
    });

    loading.present();
    const query = firebase.firestore().collection('events').orderBy('created', 'desc').limit(this.pageSize);

    query.onSnapshot((snapshot) => {
      const changedDocs = snapshot.docChanges();

      changedDocs.forEach((change) => {
        if (change.type === 'added') {
          // TODO
        }
        if (change.type === 'modified') {
          for (let i = 0; i < this.events.length; i++) {
            if (this.events[i].id == change.doc.id) {
              this.events[i] = change.doc;
            }
          }
        }
        if (change.type === 'removed') {
          // TODO
        }
      })
    })

    query.get()
      .then((events) => {

        events.forEach((event) => {
          this.events.push(event);
        });

        loading.dismiss();

        if (events.size == 0) {
          this.cursor = 0;
        } else {
          this.cursor = this.events[this.events.length - 1]; // the last index of the collection
        }
        console.log(this.events);

      }).catch((err) => {
        console.log(err);
      });
  }

It looks like firebase.auth().currentUser is not set when your Feed.ts runs. 它看起来像firebase.auth().currentUserFeed.ts运行时,不会设置firebase.auth().currentUser This is expected, since the client may need to check with the server if the token is still valid, which is an asynchronous operation. 这是预期的,因为客户端可能需要检查服务器是否仍然有效,这是异步操作。

In cases like this, always use an onAuthStateChanged listener, as shown in the first snippet in the docs on getting the current signed in user . 在这种情况下,请始终使用onAuthStateChanged侦听器,如获取当前登录用户的文档中的第一个片段所示。

So something like: 所以类似于:

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    // User is signed in.
    ... code that uses the user's properties
  } else {
    // No user is signed in.
  }
});

Edit 编辑

Your new getEvents() is not a function error is caused by the fact that this has a different meaning inside a callback function that is declared as function() . 你的新getEvents() is not a function错误, this是因为它在声明为function()的回调函数中具有不同的含义。 The simplest solution here is use => notation, which maintains the value of this inside the function: 这里最简单的解决方案是use => notation,它在函数内维护this的值:

firebase.auth().onAuthStateChanged((user) => {
  if (user) {
    this.photo = user.photoURL;
    this.getEvents();
  } else {
    console.log('Not authenticated');
    // No user is signed in.
  }
});

Note that the rest of your code already uses => notation, which makes me suspect that you haven't been writing JavaScript all that long yet. 请注意,您的其余代码已经使用了=> notation,这让我怀疑您还没有编写JavaScript。 I highly recommend taking a tutorial in callback function in JavaScript, as it'll save you a lot of time and questions) going forward. 我强烈建议您在JavaScript中使用回调函数教程,因为它将为您节省大量时间和问题)。

Ohh now i fully understand , and as exacly as you said i haven't been writing too much javascript code here, as i was watiching some tutoirals and adding some other things. 哦,现在我完全理解,并且像你说的那样,我没有在这里写过多的javascript代码,因为我正在看一些tutoirals并添加一些其他的东西。 I fixed the problem and also you helped me understand a basic but important thing. 我解决了这个问题,你帮我理解了一个基本但重要的事情。 Thanks a lot for your time. 非常感谢你的时间。

暂无
暂无

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

相关问题 firebase.auth().currentUser 在页面加载时为 null - firebase.auth().currentUser is null at page load javascript firebase.auth()。currentUser = null - javascript firebase.auth().currentUser = null firebase.auth()。currentUser和onAuthStateChanged始终为null,尽管已登录 - firebase.auth().currentUser and onAuthStateChanged always null inspite of being signed in 刷新页面时,有时firebase.auth()。onAuthStateChanged返回null的用户 - Sometimes firebase.auth().onAuthStateChanged returns user of null when I refresh the page 使用 async/await 获取 firebase.auth().currentUser - Get firebase.auth().currentUser with async/await 试图使 firebase.auth().currentUser 成为 promise - Attempting to make firebase.auth().currentUser a promise Firebase auth:当我们需要使用同步 api firebase.auth().currentUser 或者它总是不好的做法? - Firebase auth: when we need to use the synchronize api firebase.auth().currentUser or it always bad practice? 使用Firebase,即使正在记录firebase.auth()。currentUser,它也是一个空值 - Using Firebase, firebase.auth().currentUser is a null value even though it is being logged firebase.auth().currentUser.getIdToken() 抛出“auth/user-token-expired”怎么办? - What to do when firebase.auth().currentUser.getIdToken() throws “auth/user-token-expired”? 使用 firebase.auth().oAuthStateChanged 在页面刷新时获取令牌 null - Getting token null on page refresh using firebase.auth().oAuthStateChanged
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM