使用 cookies 使用 angularfire2 保持登录用户

Persist logged in user with angularfire2 using cookies

我正在使用带有 angularfire2 的简单自定义身份验证和来自 Firebase 的身份验证服务。

import { Injectable } from '@angular/core';
import { AngularFire } from 'angularfire2';
import { Cookie } from 'ng2-cookies';

@Injectable()
export class GlobalMenuService {

    loggedIn: boolean = false;

    constructor(private af: AngularFire) { }

    login(email: string, password: string) {
        this.af.auth.login({
            email: email,
            password: password
        })
            .then((success) => {
                this.loggedIn = true;
            });
    }

    logout() {
        this.af.auth.logout();
        this.loggedIn = false;
    }
}

有没有办法在 cookie 中保存一些数据(令牌、uid、电子邮件或其他东西)以恢复会话,即每次用户 returns 重新登录到应用程序时,他都没有写凭据?

你应该使用 auth.subscribe()。只要身份验证状态发生变化,就会调用此函数。

this.af.auth.subscribe(user => {
  if (user) {
    // User is signed in.
    ... do other stuff
  } else {
    // No user is signed in.
    ... do other stuff
  }
});

如果您在打开应用程序时已经登录,或者您调用 signInWithEmailAndPassword,将调用此函数并且 auth 将包含您登录的用户数据。