In this plunk I have an Angular 6 module with a related service that wraps HttpClient
. The module is imported by the application module, and the main application component calls the service.
Problem is that I'm getting the following error:
Unexpected value 'MyHttpService' declared by the module 'CoreServiceModule'. Please add a @Pipe/@Directive/@Component annotation
I checked all the imports and declarations and couldn't find the problem. Where's the error?
The module:
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 {}
And the service:
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: '));
}
}
Generally as the error says, services,pipes
should be under providers of your module, remove
from declarations
and add it to providers
,
@NgModule({
imports: [
CommonModule,
HttpClientModule
]
declarations : [],
providers:[
MyHttpService
],
exports: [
]
})
Declarations are only for declarable classes
Add MyHttpService
to Providers
.
@NgModule({
imports: [
CommonModule,
HttpClientModule
]
providers:[
MyHttpService
]
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With