我对 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{}
以下是validation.service.ts的内容
import { Injectable } from '@angular/core';
@Injectable()
export class ValidationService {
static validateText(control) {
//do something
}
}
现在我尝试使用 component2
中的 ValidationService
,为此,我在 模块中导入了
如下:SharedModule
组件2
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
,除非我在上面的文件中再次导入它。
我的问题是,既然我已将 SharedModule
导入到component2 模块和 SharedModule 已经提供 Service
了吗?我在这里缺少什么?这根本不可能吗?
最佳答案
将服务添加到 @NgModule()
的 imports: []
会将其注册到依赖项注入(inject)框架 (DI)。
通过将其列在构造函数参数中,您可以指示 DI 在创建组件实例时将服务传递给构造函数。
constructor(private validationService:ValidationService){
为了让 TypeScript 知道您的意思是 ValidationService
(您的项目或导入的模块中可能有多个),您需要添加一个导入来明确这一点。
之后你就可以像这样使用它
this.validationService...
关于angular - 来自共享模块的服务不可见 - Angular 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46235403/