10

I've encountered a problem with injecting services in angular 5 as in tutorial.

I have a simple service

@Injectable() export class SimpleService { ... } 

And a simple component:

@Component({...}) export class SimpleComponent { constructor(private simpleService SimpleService) {} } 

A service is set to providers in module:

@NgModule({ ... providers: [SimpleService] ... }) export class SimpleModule {} 

I see the following error in console:

Error: Can't resolve all parameters for SimpleComponent 

However, if I inject the SimpleService with @Inject like

@Inject(SimpleService) private simpleService: SimpleService 

the error disappears.

What am I doing wrong?

UPDATE: I saw several answers where people advise to add emitDecoratorMetadata: true to tsconfig file. But this line is already there

2 Answers 2

6

It turned out that the reason for this error was an incorrect import of polyfills.ts. Previously I ejected my cli app and removed polyfills entry point from my webpack config. After that I imported them in my main.ts. But I imported polyfills after I imported AppModule. After I moved import './polyfills.ts' statement to the top of the file the error disappeared.

Another option for fixing this error is moving to AOT compilation:

module: { rules: [ ... { "test": /(?:\.ngfactory\.js|\.ngstyle\.js|\.ts)$/, "use": [ "@ngtools/webpack" ] } ] } plugins: [ ... new AngularCompilerPlugin({ mainPath: 'main.ts', platform: PLATFORM.Browser, hostReplacementPaths: { 'environments/environment.ts': 'environments/environment.ts' }, sourceMap: true, tsConfigPath: 'src/app/tsconfig.json', skipCodeGeneration: false // this line is responsible for AOT }) ] 

If you use AOT compilation instead JIT you won't need emitDecoratorMetadata in your tsconfig.

Sign up to request clarification or add additional context in comments.

Comments

2

I had a similar issue and this may help others, as this was the closest match I found while searching.

I had an error in my constructor function. I forgot to declare the type of the Service:

I had written:

constructor( private myService ){} 

instead of:

constructor( private myService: MyService ){} 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.