【问题标题】:Get Firebase $key after Creating the Object创建对象后获取 Firebase $key
【发布时间】:2016-11-02 17:26:07
【问题描述】:

我有一个使用 AngularFire2 的 Angular 2 (2.0.0) 项目,我想创建一个流程,在其中创建一个新用户(Firebase 身份验证),然后根据用户对象中提供的组织名称创建一个新客户,然后最后创建一个包含客户密钥和用户密钥的用户配置文件。

我的服务都可以正常工作,只是想弄清楚如何获取刚刚添加的对象的 $key。或者,如果我以错误的方式处理此问题,也许可以就另一种方法获得相同结果的一些建议。

注册服务

import { Injectable } from '@angular/core';
import { FirebaseAuth } from 'angularfire2/index';

import { AuthenticationService } from './authentication.service';
import { CustomerService } from '../customer/customer.service';
import { UserService } from '../user/user.service';
import { User, UserProfile } from "./user-model";


@Injectable()
export class RegistrationService {

  customer: Object;

  constructor(
    // private auth: FirebaseAuth,
    private authenticationService: AuthenticationService,
    private customerService: CustomerService,
    private userProfileService: UserService) {
  }

  registerNewAccount(user: User) {

    // Step 1 - Create new user based on Email and Password Provided
    this.authenticationService.createNewUser(user);

    // Step 2 - Create new object with Organisation Name to push to Customer Service
    this.customer = new Object({
      organisation: user.organisation
    });

    // Step 3 - Create new Customer with object created above
    this.customerService.addCustomer(this.customer);

    // Create new User Profile with link to User and Customer
    var userProfile = new UserProfile();

    // This is the problem i am trying to solve
    userProfile.userId='I want to get the $key from the user just created above';
    userProfile.organisation='I want to get the $key for the customer just created';

    return this.userProfileService.addUser(userProfile);

  }

}

身份验证服务

import { Injectable, Inject } from "@angular/core";
import { Observable, Subject, BehaviorSubject } from 'rxjs/Rx';
import { FirebaseAuth, FirebaseAuthState, FirebaseRef, AngularFireDatabase } from 'angularfire2/index';

import { User } from "./user-model";
import { AuthInfo } from './auth-info';

import { Router } from "@angular/router";

declare var firebase: any;

@Injectable()
export class AuthenticationService {

  user: User;

  sdkDb: any;
  customer: any;
  usersRef: string = '/users/';
  customersRef: string = '/customers/';
  static UNKNOWN_USER = new AuthInfo(null);
  authInfo$: BehaviorSubject<AuthInfo> = new BehaviorSubject<AuthInfo>(AuthenticationService.UNKNOWN_USER);

  constructor(
    private auth: FirebaseAuth,
    private db: AngularFireDatabase,
    @Inject(FirebaseRef) fb,
    private router: Router) {
    this.sdkDb = fb.database().ref();
  }

  getCurrentUserId() {

    firebase.auth().onAuthStateChanged(function (user) {

      if (user) {
        this._userId = firebase.database().ref() + (firebase.auth().currentUser.uid);
        return this._userid;
      }
    });
  }

  createNewUser(user: User): Observable<any> {

    return this.fromFirebaseAuthPromise(this.auth.createUser(user));

  }

  signinUser(email, password): Observable<FirebaseAuthState> {

    return this.fromFirebaseAuthPromise(this.auth.login({ email, password }));

  }

  fromFirebaseAuthPromise(promise): Observable<any> {
    const subject = new Subject<any>();

    promise
      .then(res => {
        const authInfo = new AuthInfo(this.auth.getAuth().uid);
        this.authInfo$.next(authInfo);
        subject.next(res);
        subject.complete();
      },
      err => {
        this.authInfo$.error(err);
        subject.error(err);
        subject.complete();
      });

    return subject.asObservable();
  }

  logout() {
    firebase.auth().signOut();
    this.router.navigate(['/home']);
  }

  private postSignIn(): void {
    this.router.navigate(['/customer/list']);
  }

  firebaseUpdate(dataToSave) {
    const subject = new Subject();

    this.sdkDb.update(dataToSave)
      .then(
      val => {
        subject.next(val);
        subject.complete();

      },
      err => {
        subject.error(err);
        subject.complete();
      }
      );

    return subject.asObservable();
  }
}

客户服务

import { Injectable, Inject, forwardRef } from '@angular/core';

import { Observable, Subject } from "rxjs/Rx";

import { FirebaseRef, AngularFireDatabase, FirebaseListObservable } from 'angularfire2';

import "rxjs/add/operator/filter";

import { Customer } from "./customer-model";
import { AuthenticationService } from '../authentication/authentication.service';

declare var firebase: any;

@Injectable()
export class CustomerService {

    sdkDb: any;
    customersRef: string = '/customers/';
    authService: AuthenticationService;


    customer: Customer;
    customers: FirebaseListObservable<Customer[]>;

    constructor(
        private db: AngularFireDatabase,

        @Inject(FirebaseRef) fb
    ) {

        this.sdkDb = fb.database().ref();
    }

    getCustomers(): Observable<Customer[]> {

        return this.db.list(this.customersRef, {
            query: {
                orderByChild: 'organisation'
            }
        })
            .map(Customer.fromJsonList)

    }

    getCustomer(customerIndex: string) {

        this.db.object('/customers/' + customerIndex)
            .subscribe(customer => {
                this.customer = customer;
            });
        return this.customer;
    }

    addCustomer(customer: any) {

        const newCustomer = Object.assign({}, customer);

        const newCustomerKey = this.sdkDb.child(this.customersRef).push().key;

        let dataToSave = {};

        dataToSave[this.customersRef + newCustomerKey] = newCustomer;

        return this.firebaseUpdate(dataToSave);

    }

    updateCustomer(customerIndex: string, customer: Customer): Observable<any> {

        const customertoSave = Object.assign({}, customer);

        let dataToSave = {};
        dataToSave[this.customersRef + customerIndex] = customertoSave;

        return this.firebaseUpdate(dataToSave);

    }

    deleteCustomer(customerIndex: string) {
        this.db.object(this.customersRef + customerIndex).remove();
    }

    firebaseUpdate(dataToSave) {
        const subject = new Subject();

        this.sdkDb.update(dataToSave)
            .then(
            val => {
                subject.next(val);
                subject.complete();

            },
            err => {
                subject.error(err);
                subject.complete();
            }
            );

        return subject.asObservable();
    }

}

用户配置文件服务

import { Injectable, Inject } from '@angular/core';

import { Observable, Subject } from "rxjs/Rx";

import { UserProfile } from "./user-model";

import { FirebaseRef, AngularFireDatabase, FirebaseListObservable, FirebaseObjectObservable } from 'angularfire2';

import "rxjs/add/operator/filter";

declare var firebase: any;

@Injectable()
export class UserService {

    sdkDb: any;
    usersRef: string = '/users/';

    user: UserProfile;
    users: FirebaseListObservable<UserProfile[]>;

    constructor(
        private db: AngularFireDatabase, @Inject(FirebaseRef) fb) {
        this.sdkDb = fb.database().ref();
    }

    getUsers(): Observable<UserProfile[]> {

        return this.db.list(this.usersRef, {
            query: {
                orderByChild: 'organisation'
            }
        })
        .map(UserProfile.fromJsonList)
        .do(console.log);

    }

    getUser(userIndex: string) {

        this.db.object('/users/' + userIndex)
            .subscribe(user => {
                this.user = user;
            });
        return this.user;
    }

    addUser(user: any) {

        const newUser = Object.assign({}, user);

        const newUserKey = this.sdkDb.child(this.usersRef).push().key;

        let dataToSave = {};

        dataToSave[this.usersRef + newUserKey] = newUser;

        return this.firebaseUpdate(dataToSave);

    }

    updateUser(userIndex: string, user: UserProfile): Observable<any> {

        const usertoSave = Object.assign({}, user);

        let dataToSave = {};
        dataToSave[this.usersRef + userIndex] = usertoSave;

        return this.firebaseUpdate(dataToSave);

    }

    deleteUser(userIndex: string) {
        this.db.object(this.usersRef + userIndex).remove();
    }

    firebaseUpdate(dataToSave) {
        const subject = new Subject();

        this.sdkDb.update(dataToSave)
            .then(
            val => {
                subject.next(val);
                subject.complete();

            },
            err => {
                subject.error(err);
                subject.complete();
            }
            );

        return subject.asObservable();
    }

}

【问题讨论】:

  • 为什么不像在客户服务中那样创建密钥?
  • 是的,我可以这样做,然后将其传递给客户服务,然后在客户服务中放置一些逻辑,说只有在构造函数中没有传递密钥时才生成密钥。我没有走那条路,因为我认为客户服务应该负责生成密钥。
  • 谢谢约翰 - 用客户密钥试过了,效果很好。我将需要查看一种获取用户密钥的方法,因为它是在创建用户时由 Firebase 动态创建的。再次感谢

标签: angular firebase firebase-realtime-database angularfire2


【解决方案1】:

正如 John 建议的那样,我首先在注册服务中创建密钥,并将其作为可选参数传递给客户服务。这意味着我可以从注册服务中访问密钥,而无需尝试查找或从 firebase 检索它。

【讨论】:

    猜你喜欢
    • 2018-06-08
    • 2018-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多