【问题标题】:Custom Validator Angular dependency injection自定义验证器 Angular 依赖注入
【发布时间】:2017-05-17 03:26:20
【问题描述】:

我正在开发 Angular/typescript 上的自定义验证器。这是我的课:

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() 方法。 但是这个组件只能是静态的。它告诉我一个错误: “Validator”类型上不存在属性“sharedDocument”。

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

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

我该如何解决这个问题?

【问题讨论】:

  • 为什么不将sharedDocument: SharedDocument 作为参数传递给amountIsValid

标签: angular typescript


【解决方案1】:

我想这是因为您的验证器从未实例化,因此 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 方法吗?

【讨论】:

    猜你喜欢
    • 2013-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-20
    • 2017-02-10
    • 1970-01-01
    相关资源
    最近更新 更多