Firebase提供了一种在应用中设置身份验证的简单方法。在这里,我们将探讨如何使用AngularFire2库为Angular 2+应用程序设置简单的电子邮件/密码注册和身份验证工作流程 。 
第一步是创建一个新的Firebase项目,并在Firebase控制台的“身份验证”部分下启用电子邮件/密码登录方法。 让我们开始使用npm安装必要的包。这会将Firebase SDK,AngularFire2和promise-polyfill依赖项添加到您的项目中: $ npm install firebase angularfire2 --save $ npm install promise-polyfill --save-exact 现在让我们将Firebase API和项目凭证添加到项目的环境变量中。如果您点击添加Firebase到您的网络应用,您可以在Firebase控制台中找到这些值: src/environments/environment.ts export const environment = {
production: false,
firebase: {
apiKey: 'XXXXXXXXXXX',
authDomain: 'XXXXXXXXXXX',
databaseURL: 'XXXXXXXXXXX',
projectId: 'XXXXXXXXXXX',
storageBucket: 'XXXXXXXXXXX',
messagingSenderId: 'XXXXXXXXXXX'
}}; 然后我们将使用AngularFireModule和AngularFireAuthModule配置我们的app模块。另请注意,我们正在导入并提供AuthService。我们接下来会创建该服务: app.module.ts // ...
import { AngularFireModule } from 'angularfire2';
import { environment } from '../environments/environment';
import { AngularFireAuthModule } from 'angularfire2/auth';
import { AuthService } from './auth.service';
@NgModule({
declarations: [
AppComponent
],
imports: [
// ...
AngularFireModule.initializeApp(environment.firebase),
AngularFireAuthModule
],
providers: [AuthService],
bootstrap: [AppComponent]
})
export class AppModule { } 创建Auth服务 我们的服务将是一个允许我们登录,注册或注销用户的中心位置,因此我们将为这3个操作定义方法。所有的身份验证逻辑都将在服务中,这将允许我们创建不需要实现任何身份验证逻辑的组件,并有助于保持我们的组件简单。 您可以使用此命令使用Angular CLI为服务创建框架: $ ng g s auth 这是服务的实现,利用AngularFireAuth: auth.service.ts import { Injectable } from '@angular/core';
import { AngularFireAuth } from 'angularfire2/auth';
import * as firebase from 'firebase/app';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class AuthService {
user: Observable<firebase.User>;
constructor(private firebaseAuth: AngularFireAuth) {
this.user = firebaseAuth.authState;
}
signup(email: string, password: string) {
this.firebaseAuth
.auth
.createUserWithEmailAndPassword(email, password)
.then(value => {
console.log('Success!', value);
})
.catch(err => {
console.log('Something went wrong:',err.message);
});
}
login(email: string, password: string) {
this.firebaseAuth
.auth
.signInWithEmailAndPassword(email, password)
.then(value => {
console.log('Nice, it worked!');
})
.catch(err => {
console.log('Something went wrong:',err.message);
});
}
logout() {
this.firebaseAuth
.auth
.signOut();
}
} 您会注意到AngularFireAuth.auth上可用的方法都返回promise,因此我们可以使用then和catch分别处理成功和错误状态。 我们在这里使用createUserWithEmailAndPassword和signInWithEmailAndPassword,因为我们正在设置电子邮件/密码身份验证,但可以通过Twitter,Facebook或Google进行相同的方法进行身份验证。 组件类和模板 既然我们的auth服务已经到位,那么创建一个允许登录,注册或注销的组件非常简单: app.component.ts import { Component } from '@angular/core';
import { AuthService } from './auth.service';
@Component({ ... })
export class AppComponent {
email: string;
password: string;
constructor(public authService: AuthService) {}
signup() {
this.authService.signup(this.email, this.password);
this.email = this.password = '';
}
login() {
this.authService.login(this.email, this.password);
this.email = this.password = '';
}
logout() {
this.authService.logout();
}
} 我们在组件的构造函数中注入服务,然后定义调用auth服务上的等效方法的本地方法。我们使用public关键字而不是private关注服务,以便我们也可以直接从模板访问服务属性。 模板非常简单,并使用authService的用户对象上的异步管道来确定是否有登录用户: app.component.html <h1 *ngIf="authService.user | async">Welcome {{ (authService.user | async)?.email }}!</h1>
<div *ngIf="!(authService.user | async)">
<input type="text" [(ngModel)]="email" placeholder="email">
<input type="password" [(ngModel)]="password" placeholder="email">
<button (click)="signup()" [disabled]="!email || !password">
Signup
</button>
<button (click)="login()" [disabled]="!email || !password">
Login
</button>
</div>
<button (click)="logout()" *ngIf="authService.user | async">
Logout
</button> 我们的输入字段使用ngModel和框架语法中的banana,双向绑定到组件类中的电子邮件和密码值。 完成!使用Firebase身份验证向您的应用添加身份验证就是这么简单! 以上就是Angular中的Firebase身份验证的详细内容,更多请关注模板之家(www.mb5.com.cn)其它相关文章! |