Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected value declared by module in Angular 6

Tags:

angular

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: '));
    }
}
like image 749
ps0604 Avatar asked Jul 22 '18 04:07

ps0604


2 Answers

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: [

  ]
})
like image 145
Sajeetharan Avatar answered Sep 23 '22 21:09

Sajeetharan


Declarations are only for declarable classes

Add MyHttpService to Providers.

@NgModule({
  imports: [
    CommonModule,
    HttpClientModule
  ]
  providers:[ 
     MyHttpService
  ]
})
like image 39
Atul Sharma Avatar answered Sep 24 '22 21:09

Atul Sharma