我无法找到错误。
app.module.ts
...
providers: [ValidateService,AuthService]
...
我在register.component.ts中执行以下操作:
import {AuthService} from '../../services/auth.service';
...
constructor( private _validateService: ValidateService,
private _fms: FlashMessagesService,
private _authService: AuthService,
private _router: Router
) { }
...
ngOnInit() {
this._authService.uniqueUser({username:'zomh'}).subscribe(data => {
console.log("data.success: "+data.success);
if(!data.success) { // Username already exists
console.log('exists');
}
else {
console.log('does not exist');
}
});
}
按预期工作用户已经在数据库中,因此我得到了控制台中存在的用户。
我在validate.service.ts中做了非常相同的事情(我把它分解到了这一点):
import { AuthService } from './auth.service';
import { Injectable } from '@angular/core';
import { FormControl } from '@angular/forms';
@Injectable()
export class ValidateService {
constructor( public _authService: AuthService) { }
validateRegister(user) {
if(user.name == undefined || user.email == undefined || user.username == undefined || user.password == undefined)
return false;
else
return true;
}
validateEmailPattern(c: FormControl) {
const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (re.test(c.value))
return null;
else
return {invalidPattern:true};
}
validateUsernamePattern(c: FormControl) {
const re = /^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/
if (re.test(c.value))
return null;
else
return {invalidPattern:true};
}
validateUsernameIsUnique (c: FormControl) {
let ret:any;
if (c.value.length >= 3)
{
console.log(c.value);
this._authService.uniqueUser({username:'zomh'}).subscribe(data => {
if(!data.success) { // Username already exists
console.log('call from service: exists');
}
else {
console.log('call from service: does not exist');
}
});
}
return {usernameIsTaken:true};
}
}
但在这里我得到Cannot read property _authService of undefined
例外
对我而言,服务似乎没有正确注入。但我无法找到我的错误。
更新1: 所以我确实将auth服务调用复制到了构造函数及其工作中。因此必须是这样的。相关错误(?)我无法从构造函数之外的任何其他方法获取this._authService的值?
@Injectable()
export class ValidateService {
constructor( private _authService: AuthService ) {
this._authService.uniqueUser({ username: 'zomh' }).subscribe(data => {
if (!data.success) { // Username already exists
console.log('call from service: exists');
}
else {
console.log('call from service: does not exist');
}
});
}
答案 0 :(得分:0)
我认为您不能在@Injectable
和export class ValidateService {
没有那条线就试试。
答案 1 :(得分:0)
阅读完一篇文章后,我将我的方法重写为实例方法:
validateUsernameIsUnique = (c: FormControl) => {
let ret: any;
if (c.value.length >= 3) {
this._authService.uniqueUser({ username: c.value }).subscribe(data => {
if (!data.success) { // Username already exists
console.log('call from service: exists');
}
else {
console.log('call from service: does not exist');
}
});
}
...
它解决了这个问题。我仍然不确定为什么要这样做,随意添加知识