如何获取用户详细信息并检查用户是否登录angular2组件

时间:2016-11-24 22:46:02

标签: angular angularfire2

我为angularfire2身份验证调用auth.service提供服务。在那里,我想用它来检查用户是否已登录并获取登录的用户对象,以便我可以将其传递给组件并在模板中使用。

这是我的auth.service.ts

import { Injectable } from '@angular/core';
import { AngularFire, AuthProviders, AuthMethods } from 'angularfire2';

@Injectable()
export class AuthService {
 user = {};
 isLoggedIn: boolean;
  constructor(public af: AngularFire) {
    this.af.auth.subscribe(user => {
      if(user) {
        // user logged in
        this.user = user;
        this.isLoggedIn = true;
        console.log(this.user);

      }
      else {
        // user not logged in
        this.user = {};
        this.isLoggedIn = false;
      }
    });

   }

这很好用。但我似乎无法获得组件中isLoggedIn键的值。

我尝试在组件中调用它

import { AuthService } from '../auth/auth.service';
    isLoggedIn: boolean;
    constructor(private AuthService : AuthService) {

          this.isLoggedIn = this.AuthService.isLoggedIn;
    }

我的猜测是我没有以正确的方式做到这一点。 如何从auth.service到组件获取此isLoggedIn值?同样也是获取用户对象的更好方法。

1 个答案:

答案 0 :(得分:0)

您的方法存在的问题是,在您调用的另一个组件中  this.isLoggedIn = this.AuthService.isLoggedIn在构造函数中。快速解决此问题的方法是在auth.service中公开isLoggedIn,并从另一个组件访问它。一个例子是<div *ngIf="AuthService.isLoggedIn"> ......