In this plunk我有一个Angular 6模块,其相关服务包装了HttpClient
。该模块由应用程序模块导入,主要的应用程序组件调用该服务。
问题是出现以下错误:
模块声明的意外值'MyHttpService' “ CoreServiceModule”。请添加一个@ Pipe / @ Directive / @ Component 注释
我检查了所有导入和声明,但找不到问题。错误在哪里?
模块:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { HttpClientModule } from '@angular/common/http';
import { MyHttpService } from './http.service';
@NgModule({
imports: [
CommonModule,
HttpClientModule
],
declarations: [
MyHttpService
],
exports: [
MyHttpService
]
})
export class CoreServiceModule {}
服务:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
@Injectable({
providedIn: 'root'
})
export class MyHttpService {
constructor(public httpx: HttpClient) {
console.log("In the HttpClient constructor - " + this.httpx)
}
call () {
let data = { x: 1 };
this.httpx.post('response.json', data).subscribe(result => {
console.log("Http result = " + result);
}, error => console.log('There was an error: '));
}
}
答案 0 :(得分:11)
通常如错误所述, services,pipes
应该位于模块的提供者下, remove
来自 declarations
并将其添加到 providers
,
@NgModule({
imports: [
CommonModule,
HttpClientModule
]
declarations : [],
providers:[
MyHttpService
],
exports: [
]
})
答案 1 :(得分:1)
声明仅适用于可声明的类
将MyHttpService
添加到Providers
。
@NgModule({
imports: [
CommonModule,
HttpClientModule
]
providers:[
MyHttpService
]
})