【问题标题】:Injecting custom service in extending validator service angular 5在扩展验证器服务角度 5 中注入自定义服务
【发布时间】:2018-01-04 06:57:48
【问题描述】:

我正在扩展 angular 5 的验证器服务。

我想在这个验证器服务类中注入自定义服务(storageService)我该怎么做。

这是我的验证器服务类代码

import { FormControl } from '@angular/forms';
import { Validators } from '@angular/forms';
import { Injectable ,Injector} from '@angular/core';
import { AbstractControl } from '@angular/forms';
import { StorageService } from '../../shared/service/storage.service';

 // want to inject StorageService in this class
 declare var moment: any;
export class ValidatorService extends Validators {

 static addressValidator(control:FormControl)
  {
     console.log('want to use service here ')
  }
}

这里我想在这个类中注入StorageService 通常我们在构造函数中注入

我该怎么做?

【问题讨论】:

  • 你可以使用@Inject并注入它

标签: angular validation angular5 angular-reactive-forms angular-validation


【解决方案1】:

使用以下代码:

import { FormControl } from '@angular/forms';
import { Injectable ,Injector} from '@angular/core';
import { AbstractControl } from '@angular/forms';
import { StorageService } from '../../shared/service/storage.service';

 @Injectable()
export class ValidatorService {
  moment: any;
  constructor(private storageService: StorageService) {}


 public addressValidator(control:FormControl)
  {
     console.log('want to use service here ');
     if (conditionNotFullfill) {
       return { address: false; }
     }
     return null;

  }

}

现在你需要通过 DI 将你的 ValidatorService 注入到组件中 希望它会有所帮助。

【讨论】:

  • 这不起作用我已经在构造函数中声明并且已经调用了 super()
  • 为什么不扩展验证器?
  • 你不需要它。当您将在表单的验证数组中使用您的验证方法时,角度会自动将 formcontrol 对象作为参数传递给您的方法。只需验证值并返回 null 或对象。
  • 问题是这个类中已经有很多函数(我没有在那里复制代码,都是静态的)有没有解决方案? @Sandip
  • 你已将此公开并使用@Injectable()
【解决方案2】:

使用@Injectable 装饰器装饰您的自定义服务,以通知 Angular 该服务将注入另一个服务

@Injectable
export class ValidatorService extends Validators {

    constructor(private storageService: StorageService){}
}

别忘了将它们添加到 providers 数组的 app.module 中

【讨论】:

    猜你喜欢
    • 2017-07-27
    • 2016-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-02
    • 1970-01-01
    相关资源
    最近更新 更多