使用cookie持续使用angularfire2登录的用户

Мил*_*лов 5 cookies firebase firebase-authentication angularfire2 angular

我正在使用与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;
    }
}
Run Code Online (Sandbox Code Playgroud)

有没有一种方法可以将某些数据保存在Cookie(令牌,uid,电子邮件或其他内容)中以恢复会话,即,每次用户返回到应用程序时,无需登录即可重新登录?

Dev*_*lli 4

你应该使用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
  }
});
Run Code Online (Sandbox Code Playgroud)

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