如何在angular中使用sendEmailVerification()函数

时间:2017-11-30 08:15:09

标签: angular typescript firebase firebase-authentication angularfire

我正在尝试使用Angular和Google Firebase API制作电子邮件验证电子邮件。我从this link找到了sendEmailVerification()函数,但我不确定应该如何使用它或者放置该函数的位置,所以我在service.ts文件中创建了一个新函数,但我不确定我是否正确地写了这个功能。请有人帮帮我吗?

//auth.service.ts
private authState: any = null;

get currentUserId(): string {
  return (this.authState !== null) ? this.authState.uid : ''
}

signUpWithEmail(email: string, password: string) {
  return this.afAuth.auth.createUserWithEmailAndPassword(email, password)
    .then((user) => {
      this.authState;
    })
    .catch(error => {
      console.log(error)
      throw error
    });
}

emailVerfication() {
  this.authState.auth.getAuth().auth.sendEmailVerification();
}

//app.component.ts
onSignUp(): void {
  //this.clearErrorMessage()
  if (this.validateForm(this.email, this.password)) {
    this.AuthService.signUpWithEmail(this.email, this.password).catch(error => {
      this.error = error
    });
    //this.AuthService.emailVerfication();
  } else {
    this.AuthService.emailVerfication();
  }
}
<form (ngSubmit)="onSignUp()">
  <div class="form-group">
    <label for="email">Email</label>
    <input type="email" class="form-control" id="email" name="email" required [(ngModel)]="email">
  </div>

  <div class="form-group">
    <label for="password">Password</label>
    <input type="password" class="form-control" id="password" name="password" required [(ngModel)]="password">
  </div>

  <button type="submit" class="btn btn-success">Register</button>
</form>

我没有收到任何错误消息,但验证邮件未显示在我的电子邮件帐户中。如果需要更多代码段,请告诉我。

1 个答案:

答案 0 :(得分:0)

我知道这是一个古老的问题,但是我认为如果有人偶然遇到相同的问题,我会抛出这个答案。最近几天,我本人一直在处理同一问题。我不是Angular和Typescript的专家,所以如果有任何错误,我事先表示歉意。无论如何,这就是我的完成方式。

首先在AuthService中,我有我的注册函数,该函数调用Firebase函数'createUserWithEmailAndPassword',然后获取当前用户并运行'sendEmailVerification'函数,如下所示。

signup(email: string, password: string) {
    return this.afAuth.auth.createUserWithEmailAndPassword(email, password)
        .then(() => this.afAuth.auth.currentUser.sendEmailVerification()
            .then(() => {
                console.log('Please verify your email');
                alert('Please verify your email');
            }).catch((error) => {
                console.log('Error: ' + error);
            }));
}

这很有效,并且会发送验证电子邮件,但是即使用户尚未验证电子邮件地址,用户仍然可以浏览该应用程序。为了防止这种情况,我创建了一个路由防护,它实现了CanActivate,如下所示。

@Injectable()
export class RouteGuard implements CanActivate {

    constructor(private authService: AuthService, private router: Router) {
    }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        if (!this.authService.authenticated) {
            this.router.navigate(['/']);
        }
        return this.authService.authenticated;
    }
}

在您的应用程序模块文件中将路由防护添加到您的提供商:[]。

providers: [
    RouteGuard,
    ...
]

然后在app-routing.module.ts中,我将路由保护器添加到我想要保护的路径中。

const appRoutes: Routes = [
    {path: 'welcome', component: WelcomeComponent},
    {path: 'login', component: LoginComponent},
    {path: 'signup', component: SignUpComponent},
    {path: 'home', component: HomeComponent},
    {path: 'messages', component: MessagesComponent, canActivate: [RouteGuard]},
    {path: 'private', component: PrivateComponent, canActivate: [RouteGuard]},
    {path: '**', redirectTo: 'welcome', pathMatch: 'full'}
];

希望这会有所帮助。