Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 - Can't resolve all parameters for component: (?)

I started an Angular2 app and I have an issue since days !

Can't resolve all parameters for HomeComponent: (?).(…) 

But my issue is not about a particular provider : Everyting that I try to inject in my HomeComponent constructor return that error. No similars questions on that errors resolved my situation, and now I spent so much time looking for this that I can't find it.

App.moodule.ts :

  import { NgModule }      from '@angular/core';
  import { BrowserModule } from '@angular/platform-browser';
  import { RouterModule }   from '@angular/router';
  import { SimpleNotificationsModule } from 'angular2-notifications';

  // Controllers
  import { AppComponent }  from './app.component';
  import { HomeComponent }  from './components/home.component';

  // Service
  import { AuthService } from './services/auth.service';

  // Guards
  import { AuthGuard } from './guards/auth.guard';

  @NgModule({
    imports: [ 
        BrowserModule,
        RouterModule.forRoot([
        {
          path: '',
          component: HomeComponent,
          canActivate: [AuthGuard]
        }
      ]),
      SimpleNotificationsModule
    ],
    declarations: [ 
        AppComponent,
        HomeComponent
    ],
    providers: [
        AuthGuard,
      AuthService,
    ],
    bootstrap: [ AppComponent ]
  })

  export class AppModule { }

My HomeComponent :

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

import { NotificationsService } from 'angular2-notifications';

import { AuthService } from '../services/auth.service';

@Component({
    selector: 'home',
    templateUrl: '/templates/home.html'
})

export class HomeComponent implements OnInit 
{
    public test: boolean = false;

    constructor( 
        private _authService: AuthService
    ) {}

    ngOnInit()
    {
        this.test = true;
    }
}

The AuthService that I try to import is empty, and as I said every providers that I inject in HomeComponent return that error. Each constructor argument create a new question mark in the error. Let me know if you need more code, but I don't think the rest (templates, systemjs.config.js...) is the problem

like image 330
Adam S Avatar asked Dec 08 '16 17:12

Adam S


2 Answers

Import this

import {Inject} from '@angular/core';

And change your constructor to

constructor(@Inject(AuthService) _authService: AuthService) 
{

}

you should @Inject any service into constructor before using it.

and your service should be injectable

@Injectable()
export class AuthService {

}
like image 194
Jeba Prince Avatar answered Dec 03 '22 00:12

Jeba Prince


Make sure you have

"emitDecoratorMetadata": true,

in your tsconfig.js. You should not need to add @Inject() to your function parameters if that's enabled.

like image 28
Xealot Avatar answered Dec 03 '22 00:12

Xealot