Angular2 Firebase获取当前用户

时间:2017-02-06 17:04:30

标签: angular firebase firebase-authentication angularfire2

我真的很难理解如何获取登录用户的当前用户ID并按该用户ID过滤列表。

我可以轻松获得用户ID,但在通话时似乎无法获得客户列表。

如果有人可以帮助或指出我正确的方向,我们将不胜感激。

身份验证服务

import { Injectable } from "@angular/core";
import { AngularFire, AuthProviders, AuthMethods, FirebaseListObservable, FirebaseObjectObservable } from 'angularfire2';
import { UserModel } from '../users/models/user.model';

@Injectable()
export class AuthenticationService {

  public displayName: string;
  public userKey: string;
  public user: UserModel;

  constructor(public af: AngularFire) {
    this.af.auth.subscribe(
      (auth) => {
        if (auth != null) {
          this.user = this.af.database.object('users/' + auth.uid);
          this.userKey = auth.uid;
        }
      });
  }

  logout() {
    return this.af.auth.logout();
  }

  loginWithEmail(email, password) {
    return this.af.auth.login({
      email: email,
      password: password,
    },
      {
        provider: AuthProviders.Password,
        method: AuthMethods.Password,
      });
  }
}

客户服务

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { AngularFire, FirebaseListObservable, FirebaseObjectObservable } from 'angularfire2';

import { AuthenticationService } from '../authentication/authentication.service';

import { CustomerModel } from './models/customer.model';

@Injectable()
export class CustomersService {

  customersRef: string = '/customers/';
  customer: any;
  usersCustomerId: string;

  constructor(
    private af: AngularFire,
    private authService: AuthenticationService,
    private router: Router) { }

  getAllCustomers(): FirebaseListObservable<CustomerModel[]> {

    this.usersCustomerId = this.authService.userKey;
    console.log(this.usersCustomerId);

    return this.af.database.list(this.customersRef, {
      query: {
        orderByChild: 'uid',
        equalTo: this.usersCustomerId
      }
    });
  }
}

4 个答案:

答案 0 :(得分:5)

我也会在CustomersService中添加对firebase身份验证的订阅。通过这样做,我们确保当前用户ID可用。

constructor(
    private af: AngularFire,
    private router: Router) {
      this.af.auth.subscribe(auth => {
        if(auth) { 
          this.usersCustomerId = auth.uid;     
      }
  })
}

constructor(
    private af: AngularFire,
    private authService: AuthenticationService,
    private router: Router) {
      this.usersCustomerId = this.authService.userKey;
}

答案 1 :(得分:1)

AngularFire2软件包已被弃用。而是使用@angular/fire。我在服务和组件中使用以下代码。

auth.service.ts服务文件

authState: any = null;

constructor(
  private firebaseAuth: AngularFireAuth,
) {
  this.firebaseAuth.authState.subscribe( authState => {
    this.authState = authState;
  });
} 

检查用户是否通过身份验证

get isAuthenticated(): boolean {
    return this.authState !== null;
}

检查电子邮件是否已验证。如果您要发送电子邮件或启用禁用发送电子邮件按钮

get isEmailVerified(): boolean {
  return this.isAuthenticated ? this.authState.emailVerified : false;
}

当前用户ID

get currentUserId(): string {
  return this.isAuthenticated ? this.authState.uid : null;
}

获取用户数据

get userData(): any {
  if ( ! this.isAuthenticated ) {
    return [];
  }

  return [
    {
      id: this.authState.uid,
      displayName: this.authState.displayName,
      email: this.authState.email,
      phoneNumber: this.authState.phoneNumber,
      photoURL: this.authState.photoURL,
    }
  ];
}

header.component.ts组件文件

constructor(
  private auth: AuthService
) {}

header.component.html组件文件

<a href="#" *ngIf="auth.isAuthenticated" (click)="auth.signout($event)">Sign Out</a>

答案 2 :(得分:1)

经过长期研究,我找到了这种解决方案,我认为这是最好的: 在您的身份验证服务

async getUserIDAsync() {
    const user = await this.af.authState.pipe(first()).toPromise();
    console.log(user);
    return user.uid;
  }

在您的客户服务

getAllCustomers(): FirebaseListObservable<CustomerModel[]> {

    const uid = await this.authService.getUserIDAsync();
    console.log(uid);

    return this.af.database.list(this.customersRef, {
      query: {
        orderByChild: 'uid',
        equalTo: uid
      }
    });
  }

我发现使用Promises处理这些情况要容易得多,因为它们不是流,而是简单的一次性操作。

答案 3 :(得分:0)

你可以使用.subscribe()方法来检索你想要的数据,这里有一个例子:

this.authserve.auth.subscribe(user=>{
  if(user)
    this.curruser = user.email;
})
  

PS:

  1. authserve是一个AngularFireAuth instence
  2. auth是在Observable
  3. 内创建的authserve
  4. curruser只是一个简单的string变量