当前位置: 首页 > 工具软件 > AngularFire > 使用案例 >

[Angular] AuthService and AngularFire integration

滕夜洛
2023-12-01

Config AngularFire, we need database and auth module from firebase.

import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {RouterModule, Routes} from '@angular/router';
import {AngularFireModule, FirebaseAppConfig} from 'angularfire2';
import {AngularFireAuthModule} from 'angularfire2/auth';
import {AngularFireDatabaseModule} from 'angularfire2/database';
import {SharedModule} from './shared/shared.module';

export const ROUTES: Routes = [
  {
    path: 'auth',
    children: [
      {path: '', pathMatch: 'full', redirectTo: 'login'},
      {path: 'login', loadChildren: './login/login.module#LoginModule'},
      {path: 'register', loadChildren: './register/register.module#RegisterModule'}
    ]
  }
];

export const forebaseConfig: FirebaseAppConfig = {
  apiKey: "xxxxxxxx",
  authDomain: "fitness-app-a26ed.firebaseapp.com",
  databaseURL: "https://fitness-app-a26ed.firebaseio.com",
  projectId: "fitness-app-a26ed",
  storageBucket: "fitness-app-a26ed.appspot.com",
  messagingSenderId: "781493219422"
};

@NgModule({
  imports: [
    CommonModule,
    AngularFireModule.initializeApp(forebaseConfig),
    AngularFireAuthModule,
    AngularFireDatabaseModule,
    SharedModule,
    RouterModule.forChild(ROUTES)
  ]
})
export class AuthModule {}

 

For the SharedModule:

import {ModuleWithProviders, NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {ReactiveFormsModule} from '@angular/forms';

import { AuthFormComponent } from './components/auth-form/auth-form.component';
import {AuthService} from './services/auth/auth.service';


@NgModule({
  imports: [
    CommonModule,
    ReactiveFormsModule
  ],
  declarations: [
    AuthFormComponent
  ],
  exports: [
    AuthFormComponent
  ]
})
export class SharedModule {

  // We don't want multi instance for AuthService, so we need forRoot method
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: SharedModule,
      providers: [
        AuthService
      ]
    }
  }
}

We use forRoot method to register our AuthSerivce, so there won't be multi instances for it.

But in the AuthModule, we need to change a little bit:

import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {RouterModule, Routes} from '@angular/router';
import {AngularFireModule, FirebaseAppConfig} from 'angularfire2';
import {AngularFireAuthModule} from 'angularfire2/auth';
import {AngularFireDatabaseModule} from 'angularfire2/database';
import {SharedModule} from './shared/shared.module';

export const ROUTES: Routes = [
  {
    path: 'auth',
    children: [
      {path: '', pathMatch: 'full', redirectTo: 'login'},
      {path: 'login', loadChildren: './login/login.module#LoginModule'},
      {path: 'register', loadChildren: './register/register.module#RegisterModule'}
    ]
  }
];

export const forebaseConfig: FirebaseAppConfig = {
  apiKey: "xxxxxxxx",
  authDomain: "fitness-app-a26ed.firebaseapp.com",
  databaseURL: "https://fitness-app-a26ed.firebaseio.com",
  projectId: "fitness-app-a26ed",
  storageBucket: "fitness-app-a26ed.appspot.com",
  messagingSenderId: "781493219422"
};

@NgModule({
  imports: [
    CommonModule,
    AngularFireModule.initializeApp(forebaseConfig),
    AngularFireAuthModule,
    AngularFireDatabaseModule,
    SharedModule.forRoot(),
    RouterModule.forChild(ROUTES)
  ]
})
export class AuthModule {}

 

AuthService is the serivce which talk to Firebase Auth Module:

import {Injectable} from '@angular/core';
import {AngularFireAuth} from 'angularfire2/auth';

@Injectable()
export class AuthService {
  constructor(
    private af: AngularFireAuth
  ) {

  }

  createUser(email: string, password: string) {
    return this.af.auth.createUserWithEmailAndPassword(email, password);
  }

  loginUser(email: string, password: string) {
    return this.af.auth.signInWithEmailAndPassword(email, password)
  }
}

 

Register user:

import {Component} from '@angular/core';
import {FormGroup} from '@angular/forms';
import {AuthService} from '../../../shared/services/auth/auth.service';
@Component({
  selector: 'register',
  template: `
    <div>
      <auth-form (submitted)="registerUser($event)">
        <h1>Register</h1>
        <a routerLink="/auth/login">Already have an account?</a>
        <button type="submit">Create account</button>
        <div class="error" *ngIf="error">
          {{error}}
        </div>
      </auth-form>
    </div>
  `
})
export class RegisterComponent {

  error: string;

  constructor(
    private authService: AuthService
  ) {

  }

  async registerUser(event: FormGroup) {
    const {email, password} = event.value;
    try {
      await this.authService.createUser(email, password);
    } catch(err) {
      this.error = err.message;
    }
  }
}

 

login user:

import {Component} from '@angular/core';
import {FormGroup} from '@angular/forms';
import {AuthService} from '../../../shared/services/auth/auth.service';

@Component({
  selector: 'login',
  template: `
    <div>
      <auth-form (submitted)="loginUser($event)">
        <h1>Login</h1>
        <a routerLink="/auth/register">Not registered?</a>
        <button type="submit">Login</button>
        <div class="error" *ngIf="error">
          {{error}}
        </div>
      </auth-form>
    </div>
  `
})
export class LoginComponent {

  error: string;

  constructor(
    private authService: AuthService
  ) {

  }

  async loginUser(event: FormGroup) {
    const {email, password} = event.value;
    try {
      await this.authService.loginUser(email, password);
    } catch(err) {
      this.error = err.message;
    }
  }
}

 

转载于:https://www.cnblogs.com/Answer1215/p/7292512.html

 类似资料: