Observablerxjs
Observablerxjs

Reputation: 722

AoT errors in production mode

So in my project I have components and services and I have included services where I need them. To do so I declared all the services as private in the constructor. For example:

constructor(private myService: MyService) {}

But in the html template I have used the service like ([ngModel])="myService.name". And here is the issue, when I tried to build in production mode I had a lot of AoT errors saying that I was using a private property which was only accessible within the class for each service I used in an html template. So I was wondering if it's a good practice to declare all the services as public to avoid the AoT errors.

Upvotes: 1

Views: 95

Answers (2)

Kim Kern
Kim Kern

Reputation: 60357

Yes, you need to declare instance variables (e. g. your service) as public if you want to use them in a template. Alternatively, declare a public method in your class so you don't have to use your service directly:

constructor(private userService: UserService) {}

getUsers(): User[] {
  return this.userService.getUsers();
}

Also, I'd recommend that you use AOT during development so that you get notified about those errors immediately. It should not take much longer anymore. ng serve --aot

Upvotes: 1

Igor
Igor

Reputation: 62213

You can either

  • Add a public accessor to the property on the component that calls through to the service.

    get name():string {return this.myService.name;}
    
  • Change private to public in the constructor

    constructor(public myService: MyService) {}
    

As far as which of these 2 is "correct" is a matter of opinion.

Upvotes: 2

Related Questions