Reputation: 671
Hello I don't understand why it's not injected properly. It throws this error:
Cannot read property 'productService' of undefined
at ProductValidator.validateCodeUnique (product-validator.ts:23)
@Injectable()
export class ProductValidator {
constructor(public productService: ProductService) { }
validateCodeUnique(input: FormControl) {
const code: string = input.value;
let isUnique = true;
this.productService.getAllProducts().forEach((product, key) => {
if (product.code === code) {
isUnique = false;
}
});
return isUnique ? null : { notValid: true };
}
}
validateCodeLength(input: FormControl) {
const codeLength: number = input.value.length;
const hasIncorrectLength = codeLength < 1 || codeLength > 10;
return hasIncorrectLength ? null : { notValid: true };
}
ProductService is also annotated as Injectable
:
@Injectable()
export class ProductService {
...
}
I declared both in module's providers:
providers: [ProductService, ProductValidator]
And I'm calling Validator from another modal window:
export class AddDialogComponent {
code = new FormControl('', [this.productValidator.validateCodeLength, this.productValidator.validateCodeUnique]);
constructor(public dataService: ProductService,
public productValidator: ProductValidator)
...
}
validateCodeLength
works fine, does someone has any idea why ProductService isn't injected? I'm injecting ProductService in another components where it works great. Have no idea what I'm missing here
Upvotes: 1
Views: 83
Reputation: 401
I reproduced your error and you, actually, have to bind a context variable to your validation function every time you need to access it (i.e. the this variable).
I always did a myValidationFunction.bind(this)
to those cases since the validation function was always declared in the same Component that the FormControl was being created but your case is an specific one.
In order to make your code run I had to:
this.productValidator.validateCodeUnique.bind(this.productValidator)
This is because you do not want the context variable this (inside the validation function) to be an instance of your AddDialogComponent where you create the FormControl, you actually want it to be a ProductValidator instance.
Hope it helps.
Upvotes: 1