来自共享模块的服务是不可见的 - Angular 4
问题描述:
我对Angular 4的知识只是初学者级别。我试图从如下一些部件共享模块提供的服务:来自共享模块的服务是不可见的 - Angular 4
项目结构
app
|_ component1
|_ .css
|_ .html
|_ .component.ts
|_ .module.ts
|_ component2
|_ //same as above
|_ shared
|_ messages.components.ts
|_ number.directive.ts
|_ shared.module.ts
|_ validation.service.ts
问题
现在我有我的shared.module.ts为如下:
//Certain other imports
import { ValidationService } from './validation.service';
@NgModule({
declarations: [...],
imports : [....],
exports : [....],
providers : [ValidationService]
});
export class SharedModule{}
B elow是validation.service.ts
import { Injectable } from '@angular/core';
@Injectable()
export class ValidationService {
static validateText(control) {
//do something
}
}
内容现在我试图消耗component2
的ValidationService
和那个,我的component2
如下模块进口SharedModule
:
component2.module.ts
import { SharedModule } from './../shared/shared.module';
//some other imports
@NgModule({
declarations: [],
imports: [SharedModule]
})
export class Component2Module { }
和component2.com ponent.ts是如下:
import { SharedModule } from './../shared/shared.module';
//other imports
@Component({
selector: 'app-root',
templateUrl: './component2.component.html',
styleUrls: ['./component2.component.css']
})
export class Component2Component implements OnInit{
constructor(){
}
ngOnInit() {
this.sampleForm = new FormGroup({
sampletxt : new FormControl('', [Validators.required , ValidationService.validateText]), //this method here
});
}
}
,但我不能,除非我在上面的文件重新导入它使用这个ValidationService
。
我在这里的问题是,为什么我不能够使用ValidationService
没有将其导入我component2
因为我已经导入SharedModule
到COMPONENT2模块和SharedModule已经提供Service
?我在这里错过了什么?这根本不可能?
答
将服务添加到imports: []
的@NgModule()
将其注册到依赖注入框架(DI)。
通过将其列入构造函数参数中,您可以指示DI在创建组件实例时将该服务传递给构造函数。
constructor(private validationService:ValidationService){
为打字稿知道你的意思ValidationService
(有可能是在你的项目或进口的模块数),你需要添加导入,使这一点。
之后,你可以使用它像
this.validationService...
谢谢你的简短。这里有一点疑问。我在Service中有静态方法。那么这里需要将它添加到构造函数中吗? –
只是不要在服务中使用静态方法。如果你想使用一个服务的静态方法,它实际上不是一个服务,不应该这样对待。不需要在任何地方向'import:[...]或者'providers:[']'添加这样一个类,它只需要一个TypeScript导入。 –
不客气。好主意。 Angular花了很长时间制作了一个可以轻松测试的框架。使用静态方法可以再次发挥这一巨大优势。 –