【问题标题】:Angular2 Firebase Get Current UserAngular2 Firebase 获取当前用户
【发布时间】:2017-02-06 17:04:29
【问题描述】:

我真的很难理解如何获取登录用户的当前用户 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
      }
    });
  }
}

【问题讨论】:

    标签: angular firebase firebase-authentication angularfire2


    【解决方案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】:

      我也会在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;
      }
      

      【讨论】:

        【解决方案3】:

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

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

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

        【讨论】:

          【解决方案4】:

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

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

          PS:

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

          【讨论】:

            猜你喜欢
            • 2020-11-30
            • 2017-04-06
            • 2020-03-29
            • 2021-03-05
            • 2020-03-03
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-11-08
            相关资源
            最近更新 更多