Angularfire2 auth против данных пользователей firebase - PullRequest
0 голосов
/ 19 сентября 2018

У меня есть эта страница запуска, которая создает пользователей в аутентификации firebase.Мне также нужно, чтобы пользователи присутствовали в качестве объектов в Firebase DB, чтобы потом иметь возможность назначать им роли администратора, клиента или редактора.Вот мои файлы:

singup.html

<div class="login-page" [@routerTransition]>
    <div class="row">
        <div class="col-md-4 push-md-4">
            <img class="user-avatar" src="assets/images/logo.png" width="150px"/>
            <h1>Evolution HCC</h1>
            <div *ngIf="success" class="alert alert-success" role="alert" style="margin-left: 8px; margin-right: 8px;">
                <strong>Register successful!</strong>
            </div>
            <div *ngIf="failure" class="alert alert-danger" role="alert" style="margin-left: 8px; margin-right: 8px;">
                <strong>Error!</strong> Check all the fields below and try again.
            </div>
            <form role="form">
                <div class="form-content">
                    <div class="form-group">
                        <input required (input)="null" type="text" class="form-control input-underline input-lg" #name
                               name="fullName" placeholder="Full Name">
                    </div>

                    <div class="form-group">
                        <input required (input)="null" type="text" class="form-control input-underline input-lg" #name
                               name="display_name" placeholder="Display Name">
                    </div>

                    <div class="form-group">
                        <input required (input)="null" class="form-control input-underline input-lg" #email
                               name="signupMail" type="email" placeholder="Email">
                    </div>

                    <div class="form-group">
                        <input required (input)="null" type="password" class="form-control input-underline input-lg"
                               #password name="signupPassword"
                               placeholder="Password">
                    </div>

                    <div class="form-group">
                        <input required (input)="null" type="password" class="form-control input-underline input-lg"
                               #verifyPassword name="verifyPassword"
                               placeholder="Verify Password">
                    </div>
                </div>
                <button class="btn btn-m btn-primary" (click)="getItemsList()"
                        [disabled]="!(password.value === verifyPassword.value) || !name.value || !email.value || !password.value || !verifyPassword.value">
                    Register
                </button>
                <button class="btn btn-m btn-secondary" [routerLink]="['/login']"> Back to Log in</button>
            </form>
        </div>
    </div>
</div>

singup.components.ts

import {Component, OnInit} from '@angular/core';
import {routerTransition} from '../router.animations';
import {AuthService} from '../login/auth.service';
import {Router} from '@angular/router';
import {AngularFireDatabase} from "angularfire2/database-deprecated";
import {UsersService} from "../shared/services/users.service";

@Component({
    selector: 'app-signup',
    templateUrl: './signup.component.html',
    styleUrls: ['./signup.component.scss'],
    animations: [routerTransition()]
})
export class SignupComponent implements OnInit {
    currentUser: any;
    success = false;
    failure = false;

    constructor(public authService: AuthService, public db: AngularFireDatabase, public router: Router) {
    }

    ngOnInit() {
    }

    signup(email, password) {
        this.authService.signup(email, password).then(resolve => {
                this.failure = false;
                this.success = true;
                console.log('Login successfully...');
                setTimeout(function () {
                    this.router.navigate(['/login']);
                }.bind(this), 2000);
            },
            rejected => {
                this.success = false;
                this.failure = true;
                console.log('Error logging in...');
            });

    }
    updateUserData() {
        // Writes username and email to firebase db
        let path='users/${this.currentUserId}'; //End point of firebase
        let data = {
            name: this.currentUser.display_name,
        }

        this.db.object(path).update(data)
            .catch(error => console.log("error"));
    }

}

И вот мой app.module.ts

import {NgModule} from '@angular/core';
import {FormsModule} from '@angular/forms';
import {Http, HttpModule} from '@angular/http';
import {BrowserModule} from '@angular/platform-browser';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {TranslateLoader, TranslateModule} from '@ngx-translate/core';
import {TranslateHttpLoader} from '@ngx-translate/http-loader';
import {AppRoutingModule} from './app-routing.module';
import {AppComponent} from './app.component';
import {AuthGuard} from './shared';
import {AngularFireModule} from 'angularfire2';
import {AngularFireAuthModule} from 'angularfire2/auth';
import {AuthService} from './login/auth.service';
import {Ng4LoadingSpinnerModule} from 'ng4-loading-spinner';
import { AngularFireDatabase } from 'angularfire2/database-deprecated';
import { AngularFireDatabaseModule } from 'angularfire2/database';

import {ConversationComponent} from "./layout/conversation/conversation.component";
import {UsersService} from "./shared/services/users.service";
import {ConversationService} from "./layout/conversation/conversation.service";

// AoT requires an exported function for factories
export function HttpLoaderFactory(http: Http) {
    // for development
    // return new TranslateHttpLoader(http, '/start-angular/SB-Admin-BS4-Angular-4/master/dist/assets/i18n/', '.json');
    return new TranslateHttpLoader(http, '/assets/i18n/', '.json');
}

export const firebaseConfig = {
    apiKey: "$####@",
    authDomain: "######m",
    databaseURL: "#####",
    projectId: "######",
    storageBucket: "########",
    messagingSenderId: "########"
};

@NgModule({
    declarations: [
        AppComponent,
    ],
    imports: [
        BrowserModule,
        BrowserAnimationsModule,
        FormsModule,
        HttpModule,
        AppRoutingModule,
        AngularFireModule.initializeApp(firebaseConfig),
        AngularFireAuthModule,
        AngularFireDatabaseModule,
        TranslateModule.forRoot({
            loader: {
                provide: TranslateLoader,
                useFactory: HttpLoaderFactory,
                deps: [Http]
            }
        }),
        Ng4LoadingSpinnerModule
    ],
    providers: [AuthGuard, AuthService, AngularFireDatabase],
    bootstrap: [AppComponent]
})
export class AppModule {
}

также имеет singup.service.ts

import { Injectable } from '@angular/core';
import { AngularFireDatabase, AngularFireList, AngularFireObject } from 'angularfire2/database';
import { Observable } from 'rxjs/Observable';
import * as _ from 'lodash';
import {User} from "./user";

@Injectable()
export class UsersService {

    private basePath = '/users';

    itemsRef: AngularFireList<User>;
    itemRef:  AngularFireObject<User>;

    items: Observable<User[]>; //  list of objects
    item:  Observable<User>;   //   single object


    constructor(private db: AngularFireDatabase) {
        this.itemsRef = db.list('/users')
    }

    // Return an observable list with optional query
    // You will usually call this from OnInit in a component
    getItemsList(query?) {
        //const itemsRef = afDb.list('/items')
        //return this.itemsRef.valueChanges()
        return this.itemsRef.snapshotChanges().map(arr => {
            return arr.map(snap => Object.assign(snap.payload.val(), { $key: snap.key }) )
        })
    }




    // Return a single observable item
    getItem(key: string): Observable<User> {
        const itemPath = `${this.basePath}/${key}`;
        this.item = this.db.object(itemPath).valueChanges();
        return this.item
    }

    // Create a brand new item
    createItem(key: string, item: User): void {
        const user = this.db.object(`/users/${key}`);
        user.set(item);
    }


    // Update an exisiting item
    updateItem(key: string, value: any): void {
        this.itemsRef.update(key, value)
    }

    // Deletes a single item
    deleteItem(key: string): void {
        this.itemsRef.remove(key)
    }

    // Deletes the entire list of items
    deleteAll(): void {
        this.itemsRef.remove()
    }

    // Default error handling for all actions
    private handleError(error) {
        console.log(error)
    }


}

Функция updateuserdata фактически не используется страницей.Я использую шаблон, и я получил этот проект после того, как другой программист ушел, поэтому я не совсем понимаю, как он думает, что это будет работать.Я очень затронут тем фактом, что у меня есть проблемы с простыми функциями как это.У кого-нибудь есть идеи, как мне привязать мои данные к базе данных Firebase?

Я использую: шаблон администратора Angular 4 SB BS4 Angularfire2 версия 5.0.0 IDE Webstorm

...