[Angular] AuthService and AngularFire integration
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;
}
}
}
[Angular] AuthService and AngularFire integration的更多相关文章
- [AngularFire 2 ] Hello World - How To Write your First Query using AngularFire 2 List Observables ?
In this lesson we are going to use AngularFire 2 for the first time. We are going to configure the A ...
- Angular 2 技能图谱skill-map
# Angular 2 技能图谱 ## 模块 ### 自定义模块 - 根模块 - 特性模块 - 共享模块 - 核心模块 ### 内置模块 - ApplicationModule 模块 - Common ...
- [Angular] Reactive Store and AngularFire Observables
A simple store implemenet: import { Observable } from 'rxjs/Observable'; import { BehaviorSubject } ...
- [AngularFire] Angular File Uploads to Firebase Storage with Angular control value accessor
The upload class will be used in the service layer. Notice it has a constructor for file attribute, ...
- angular单元测试与自动化UI测试实践
关于本文:介绍通过karma与jsmine框架对angular开发的应用程序进行单元与E2E测试. angular单元测试与集成测试实践 先决条件 创建项目 webstorm中创建空白web项目 创建 ...
- Angular+Grunt+Bower+Karma+Protractor (Atom)
1. 配置bower 1.安装bower npm install -g bower 2.创建.bowerrc文件 { "directory": "src/bower&qu ...
- angular测试-Karma + Jasmine配置
首先讲一下大致的流程: 需要node环境,首先先要安装node,node不会?请自行搜索.版本>0.8 安装node完成之后先要测试下npm是否测试通过,如下图所示 首先看下目录结构 目录为:F ...
- angular run()运行块
和配置块不同,运行块在注入器创建之后被执行,它是所有AngularJS应用中第一个被执行的方法. 运行块是AngularJS中与main方法最接近的概念.运行块中的代码块通常很难进行单元测试,它是和应 ...
- Redux你的Angular 2应用--ngRx使用体验
Angular2和Rx的相关知识可以看我的Angular 2.0 从0到1系列第一节:Angular 2.0 从0到1 (一)第二节:Angular 2.0 从0到1 (二)第三节:Angular 2 ...
随机推荐
- IsoAlgo3d - IDF/PCF pipeline 3d viewer
IsoAlgo3d - IDF/PCF pipeline 3d viewer eryar@163.com Key Words. IDF, PCF, IsoAlgo, 3D 当前国际主流管道设计软件都可 ...
- OcadeToolkit - From 2D CAD to PDMS
OcadeToolkit - From 2D CAD to PDMS eryar@163.com Abstract. 基于开源二维CAD软件QCAD开发的插件可以将DXF文件中直线.圆弧转换到PDMS ...
- LinkedIn Cubert 实践指南
· LinkedIn Cubert安装指南 · Understanding Cubert Concepts(一)Partitioned Blocks · Understanding Cubert Co ...
- FormData是什么
FormData是什么 一.总结 一句话总结:利用 FormData 对象,可以通过JavaScript键值对来模拟一系列表单控件,还可以使用 XMLHttpRequest的send() 方法来异步提 ...
- Gym 100952 D. Time to go back
http://codeforces.com/gym/100952/problem/D D. Time to go back time limit per test 1 second memory li ...
- mysql查询最新一组数据
public function getDetail(){ $sql = "SELECT * FROM (SELECT * FROM Z_CFTC_GOV_NEW ORDER BY UPDAT ...
- enable&&builtin---shell内部命令
用enable命令显示所有激活的内部命令: [root@localhost ~]# enable -a builtin命令用于执行指定的shell内部命令,并返回内部命令的返回值 [root@xiao ...
- sleep---暂停指定的时间
sleep命令可以用来将目前动作延迟一段时间. 使用权限:所有使用者. 语法 sleep [--help] [--version] number[smhd] 参数说明: --help : 显示辅助讯息 ...
- 小米开源文件管理器MiCodeFileExplorer-源码研究(8)-文件排序工具类FileSortHelper
FileSortHelper的核心功能就是,对文件集合FileInfo排序.FileInfo有若干字段,根据字段定义了4种比较器Comparator.调用示例:Collections.sort(Lis ...
- Interrupt distribution scheme for a computer bus
A method of handling processor to processor interrupt requests in a multiprocessing computer bus env ...