自定义验证器角度依赖注入

时间:2017-05-16 13:21:06

标签: angular typescript

我正在研究Angular / typescript上的自定义Validator。这是我的班级:

export class Validator {
    constructor(private sharedDocument: SharedDocument) { }

    static amountIsValid(control: FormControl): any {
        return new Promise(resolve => {
            setTimeout(() => {
                console.log(Number.parseInt(control.value), "control.value");
                if (Number.parseInt(control.value) >= this.sharedDocument.getNewRestToPay()) {
                    resolve({
                        "error !": true
                    });
                }
                else {
                    resolve(null);
                }
            }, 50);
        });
    }
}

如您所见,我尝试通过DI从另一个组件调用getNewRestToPay()方法。 但是这个组件只能是静态的。它告诉我一个错误: 财产' sharedDocument'类型'验证器'。

上不存在

如果我使用静态组件,我需要将组件侧的方法更改为静态方法。在这种情况下,我无法回归我所需的财产。

@Injectable()
export class SharedDocument {
//some code
getNewRestToPay() :any{
        return this.restCaisse;
    }
}

我如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

我想猜测这是因为您的Validator永远不会被实例化,因此DI永远不可用。

您也可以内联创建依赖注入(而不是通过构造函数) - 这可以解决您的问题。

导入Reflective Injector

import { ReflectiveInjector } from '@angular/core';

像这样改变你的方法

    static amountIsValid(control: FormControl): any {
            return new Promise(resolve => {
                setTimeout(() => {
                    console.log(Number.parseInt(control.value), "control.value");
                    if (Number.parseInt(control.value) >= 
                        let injector = ReflectiveInjector.resolveAndCreate([SharedDocument]);
                        let sharedDocument = injector.get(SharedDocument);
                        sharedDocument.getNewRestToPay()) {
                        resolve({
                            "error !": true
                        });
                    }
                    else {
                        resolve(null);
                    }
                }, 50);
            });
        }

编辑:但就像其他评论者提到的那样 - 你真的需要在这种情况下使用DI吗?你能不能简单地将SharedDocument实例传递给amountIsValid方法?

相关问题