Search code examples
angularbuildcode-injection

Angular: Injection does not build in production build


I'm using Angular 5.1.1. I have an app with a navigation service which I inject into my components.

The Service

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

The Component:

import { Component } from '@angular/core';
import { NavigationService } from './services/navigation.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.less'],
  providers: [NavigationService]
})
export class AppComponent {
  title = 'App Title';
  constructor(private navigationService: NavigationService) { }
}
<div *ngIf="navigationService.navigationModel != null">
  <app-navigation-head></app-navigation-head>
  <div class="flex-container">
    <div class="nav-container">
      <app-navigation-side></app-navigation-side>
    </div>
    <div class="page-container">
      <app-data-page></app-data-page>
    </div>
  </div>
</div>

When I run the app with ng serve, everything is fine. Also when I build it with ng build. The injection works and the app is working fine. But when I want to build it as production with ng build --prod I get the error:

ERROR in src/app/app.component.html(1,6): : Property 'navigationService' is private and only accessible within class 'AppComponent'.

But why? Do I something wrong with the injection?


Solution

  • Adding the answer for future readers.

    If you are using the variable navigationService within your template file, then this is an error if you build using aot.

    It is recommended but not necessary to build using aot for production. But when you do so, make sure your private variables are accessed only within the same .ts file. And not even from .html or template file.

    Also check this to know what is allowed and what is not allowed in aot.