5

我正在使用带有 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、电子邮件或其他东西)中以恢复会话,即每次用户返回应用程序时重新登录他而无需编写凭据?

4

1 回答 1

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
  }
});

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

于 2016-07-04T19:06:31.500 回答