我對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
?我在這裏錯過了什麼?這根本不可能?
謝謝你的簡短。這裏有一點疑問。我在Service中有靜態方法。那麼這裏需要將它添加到構造函數中嗎? –
只是不要在服務中使用靜態方法。如果你想使用一個服務的靜態方法,它實際上不是一個服務,不應該這樣對待。不需要在任何地方向'import:[...]或者'providers:[']'添加這樣一個類,它只需要一個TypeScript導入。 –
不客氣。好主意。 Angular花了很長時間製作了一個可以輕鬆測試的框架。使用靜態方法可以再次發揮這一巨大優勢。 –