我需要实现验证码以防止垃圾邮件攻击等。但是我搜索并尝试找到有关如何在 Angular 17(使用独立组件)中执行此操作的内容越多,我就越觉得没有办法做到这一点。
我几乎完成了项目,所以我不想让它成为非独立的。我看到有 ng-recaptcha 文档和很多教程,其中 recaptcha 模块放置在 @NgModule 中的提供程序中,但我找不到如何在 app.config.ts 中提供 recaptcha。
“ng-recaptcha”:“^13.2.1”,
我尝试在不提供应用程序配置的情况下执行此操作,但出现错误,没有 recaptchV3 的提供程序。也没有提供它,我无法指定我的站点密钥。 我尝试过的代码示例:
import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import {
FormControl,
FormGroup,
ReactiveFormsModule,
Validators,
} from '@angular/forms';
import { ModalComponent } from '../../shared/modal/modal.component';
import { UserService } from '../../shared/user.service';
import { ToastrService } from 'ngx-toastr';
import { ReCaptchaV3Service } from 'ng-recaptcha';
import { environment } from '../../../environments/environment.development';
@Component({
selector: 'app-username-change-modal',
standalone: true,
templateUrl: './username-change-modal.component.html',
styleUrl: './username-change-modal.component.css',
imports: [CommonModule, ReactiveFormsModule, ModalComponent],
})
export class UsernameChangeModalComponent implements OnInit {
usernameForm!: FormGroup;
constructor(
private userService: UserService,
private toastr: ToastrService,
private recaptchaV3Service: ReCaptchaV3Service
) {}
ngOnInit(): void {
this.usernameForm = new FormGroup({
username: new FormControl(null, [
Validators.required,
Validators.minLength(3),
]),
});
}
onSubmit() {
this.recaptchaV3Service.execute('changeUsername').subscribe((token) => {
token
? this.userService
.changeUsername(this.usernameForm.value.username)
.subscribe(() => {
this.toastr.success('Username changed successfully');
})
: this.toastr.error('Recaptcha failed');
});
}
}
为了将 ReCaptcha 与 Angular 17 独立组件一起使用,请执行以下操作:
在你的
app.config.ts
export const appConfig: ApplicationConfig = {
providers: [
provideRouter(
routes,
),
provideClientHydration(),
provideAnimations(),
{ provide: RECAPTCHA_V3_SITE_KEY, useValue: environment.siteKeyV3 },
{
provide: RECAPTCHA_SETTINGS,
useValue: {
siteKey: environment.siteKeyV2,
} as RecaptchaSettings,
},
],
然后在您的组件中,您需要从
ng-recaptcha
导入 Recaptcha 模块
@Component({
selector: 'your-component',
standalone: true,
imports: [ReactiveFormsModule, RecaptchaModule,
RecaptchaFormsModule,
RecaptchaV3Module,],
templateUrl: './your-component.component.html',
styleUrl: './your-component.component.scss'
})
希望有帮助!!