【发布时间】:2020-04-01 03:40:33
【问题描述】:
我正在尝试设置一个表单字段来检查电子邮件是否存在。我已经查看了一些示例,并且验证工作正常,但是当我实现 http 管道时,映射到我的服务的 Observable,它会将其作为 null 抛出?我可以假设我从我的服务中错误地管道到它,但我不太确定。
有人可以帮助我吗?
core.js:6014 ERROR TypeError: Cannot read property 'emailService' of undefined
app.component.ts
export class AppComponent implements OnInit {
signUpForm: FormGroup;
constructor(private fb: FormBuilder, private emailService: EmailService) { }
ngOnInit() {
this.signUpForm = this.fb.group({
name: ['', Validators.required],
email: ['', [Validators.required], [this.validateEmailNotTaken]]
});
}
//Validator for checking if email name is taken or not
validateEmailNotTaken(control: AbstractControl): Observable<{ [key: string]: any } | null> {
if (control.value === null || control.value.length === 0) {
return of(null);
}
else {
return timer(1000).pipe(
switchMap(() => {
this.emailService.checkEmailExists(control.value).pipe(
map(res => {
//Do what with response
console.log(res);
if (!res) {
return { taken: true };
}
return of(null);
})
);
})
);
}
}
}
email.service.ts
interface IServerCheckEmailExists {
"available": boolean;
}
export interface ICheckEmailExists {
taken: boolean;
}
@Injectable({ providedIn: 'root' })
export class EmailService {
constructor(private _http: HttpClient) {
}
checkEmailExists(email: string): Observable<ICheckEmailExists[]> {
var postObject = {"action": "checkEmailExists"};
return this._http.post<IServerCheckEmailExists[]>("myapiurl/" + email, postObject).pipe(
map(o => o.map((sp): ICheckEmailExists => ({
taken: sp.available
})))
);
}
}
【问题讨论】:
-
您是否将 emailservice 正确导入到 appcomponent 中?
-
要重现该问题,需要进行堆栈闪电战。
-
是的,我在示例代码中省略了导入,但我有
import { EmailService } from '../_services'; -
我是否正确访问了
pipe(switchMap()中的emailService.checkEmailExists()?
标签: angular rxjs angular-forms angular-observable