创建对象后获取Firebase $键

时间:2016-11-02 17:26:08

标签: angular firebase firebase-realtime-database angularfire2

我有一个使用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();
    }

}

1 个答案:

答案 0 :(得分:-1)

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