我对Angular 4的了解只是初学者 . 我试图从某个组件中的共享模块提供服务,如下所示:
Project Structure
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
Problem
现在我的 shared.module.ts 如下:
//Certain other imports
import { ValidationService } from './validation.service';
@NgModule({
declarations: [...],
imports : [....],
exports : [....],
providers : [ValidationService]
});
export class SharedModule{}
以下是 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.component.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
.
我的问题是为什么我不能在 component2
中导入 ValidationService
,因为我已经将 SharedModule
导入了component2模块而且SharedModule已经提供了 Service
?我在这里错过了什么?这根本不可能吗?
1 回答
将服务添加到
@NgModule()
@NgModule()
将其注册到依赖注入框架(DI) .通过在构造函数参数中列出它,您可以指示DI在创建组件实例时将服务传递给构造函数 .
要让TypeScript知道你的意思
ValidationService
(你的项目中可能有几个或导入的模块),你需要添加一个导入来清除它 .之后你可以像使用它一样