在扩展验证器服务角度5中注入自定义服务

时间:2018-01-04 06:57:49

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

我正在扩展角度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,通常我们注入构造函数

我怎么能在这里做到这一点?

2 个答案:

答案 0 :(得分:1)

使用以下代码:

$rootScope

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

答案 1 :(得分:0)

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

@Injectable
export class ValidatorService extends Validators {

    constructor(private storageService: StorageService){}
}

并且不要忘记将它们添加到providers数组

中的app.module中
相关问题