我使用Yeoman generator-aspnetcore-spa,我正在嘗試注入服務到我的應用程序在Angular 2 所以我在sharedConfig中添加providers: [ CommService]
「app.module.shared.ts」 當我試圖運行的應用程序,我得到無法注入服務角2與ASP核心1.1
Exception: Call to Node module failed with error: Error: Uncaught (in promise): Error: No provider for CommService! Error: No provider for CommService!
@Injectable()
export class CommService {
constructor(private http: Http) { }
getUserIP() {
return this.http.get('http://api.ipify.org/?format=json')
.map(x => x.json());
}
}
我嘗試添加的服務提供商啓動server.ts ,這就是我得到
Exception: Call to Node module failed with error: Error: Uncaught (in promise): Error: No provider for Http! (CommService -> Http) Error: No provider for Http! (CommService -> Http) at Error (native)
我有三個模塊文件
- app.module.shared.ts包含
```
export const sharedConfig: NgModule = {
bootstrap: [ AppComponent ],
declarations: [
AppComponent,
NavMenuComponent,
CounterComponent,
FetchDataComponent,
HomeComponent,
LoginComponent
],
imports: [
RouterModule.forRoot([
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
{ path: 'counter', component: CounterComponent },
{ path: 'fetch-data', component: FetchDataComponent },
{ path: 'login', component: LoginComponent },
{ path: '**', redirectTo: 'home' }
])
]
};
```
- app.module .server.ts其中包含
```
@NgModule({
bootstrap: sharedConfig.bootstrap,
declarations: sharedConfig.declarations,
imports: [
ServerModule,
...sharedConfig.imports
]
})
export class AppModule {
}
``` - app.module.client.ts包含
```
@NgModule({
bootstrap: sharedConfig.bootstrap,
declarations: sharedConfig.declarations,
imports: [
BrowserModule,
FormsModule,
HttpModule,
...sharedConfig.imports
],
providers: [
{ provide: 'ORIGIN_URL', useValue: location.origin }
]
})
export class AppModule {
}
```
所以在那裏我可以導入並注入我的服務
是的,你說得對,我正在使用HTTP,我在問題中添加了CommService代碼,我對普通的agnualr應用程序,server-client-shared中不存在的奇怪結構感到困惑。所以我在客戶端使用CommService如果當然,當我在app.module.shared.ts中添加它的提供者,這將返回沒有提供商的CommService,但我已經添加了,所以問題在哪裏?我是否需要將每個服務器添加到客戶端和服務器文件 –
如果您只在客戶端使用CommService,我建議僅在客戶端模塊中提供它,而不是在共享中提供。這可能還會消除服務器模塊中沒有提供Http服務的任何錯誤。 –
當我將它添加到app.module.client時,它的作用與此相同:CommService沒有提供程序! ' @NgModule({ 自舉:sharedConfig.bootstrap, 聲明:sharedConfig.declarations, 進口: BrowserModule, FormsModule, HTTP模塊, ... sharedConfig.imports ], 提供商: {提供: 'ORIGIN_URL',useValue:location.origin}, CommService ] }) 出口類的AppModule { } ' –