我有这个综合页面,可以在firebase的auth中创建用户。我还需要用户在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 db?
我正在使用: 角度4 SB管理模板BS4 Angularfire2版本5.0.0 IDE Webstorm