Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 HttpClient in Component Can't resolve all parameters

I started learning Angular 4 and got to the part with HTTP Client. Right now I'm trying to make an http call from the component (yes, I know I should transfer it to service, but still)

But for some reason, when I try to inject HttpClient into my Component I get the next error:

Uncaught Error: Can't resolve all parameters for PromocodeComponent: (?).

Here's the code of my component:

import { Ticket } from '../../classes/Ticket.class'
import { Component, Input } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'promocode',
  templateUrl: './promocode.template.html',
  styleUrls: ['./promocode.styles.scss']
})
export class PromocodeComponent {
  @Input() ticket: Ticket;
  state: String = "normal";
  promocode: String = "";

   constructor(private http: HttpClient) {}

  promocodeValidate(event): void{
    console.log(this.promocode);
    console.log(event);
    this.http.get('/promocode/asdasda').subscribe(data => {
      console.log(data);
    });
  }
}

And my app.module.ts:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { MovieBadgeComponent } from './movie-badge/movie-badge.component';
import { TicketComponent } from './ticket/ticket.component';
import { PromocodeComponent} from './promocode/promocode.component';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';


@NgModule({
  declarations: [
    AppComponent,
    MovieBadgeComponent,
    TicketComponent,
    PromocodeComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [ AppComponent ]
})
export class AppModule {}
like image 617
Nausik Avatar asked Oct 30 '17 10:10

Nausik


3 Answers

It turned out, for me, that I forgot the @Injectable decorator on my service. In earlier angular (>=2), i remember the @Injectable as being optional... Guess not anymore?

like image 127
Lucas Avatar answered Oct 10 '22 14:10

Lucas


Turns out, I missed

"emitDecoratorMetadata": true

in tsconfig

fml...

like image 29
Nausik Avatar answered Oct 10 '22 12:10

Nausik


I got the same error when I ran unit testing (a spec.ts file) with Angular.

The following is what I did:

     import { HttpClientModule, HttpClient } from '@angular/common/http'; 

     beforeEach(async(() => {
       TestBed.configureTestingModule({
         declarations: [ ],
         imports: [
           HttpClientModule
         ],
         schemas: [NO_ERRORS_SCHEMA],
         providers: [
           HttpClient,
         ]
       })
         .compileComponents();
      }));

and the error was gone.

like image 1
William Hou Avatar answered Oct 10 '22 12:10

William Hou